问题描述
{
chatroomid: 59,members: [2,3]
}
现在我想要做的是,获取集合流,在此过程中能够根据成员 id 将成员字符串 id 替换为相应的 Firestore 文档。
最终结果应该是这样的:
{
chatroomid: 59,members: [{
id: 2,username: Johndoe1
},{
id: 3,username: Jennydoe1
}]
}
这可以用 Dart RxDart 实现吗? 尝试这样的事情失败了:
getChatroomStream(chatroomid)
.switchMap((i) {
return Stream.value(i.members.map((e) => i.members.add(Document(path: 'Global.userRef/$e').streamData())));
})
.listen((event) {print(event);});
[VERBOSE-2:ui_dart_state.cc(177)] 未处理的异常:并发
迭代期间的修改:实例
'MappedListIterable
解决方法
class MemberInfo {
final int id;
final String? username;
final bool isLoading;
}
class Room {
final int chatroomid;
final List<int> members;
}
class RoomWithMemberInfos {
final int chatroomid;
final List<MemberInfo> infos;
factory RoomWithMemberInfos.initial(Room room) {
return RoomWithMemberInfos(
room.chatroomid,room.members
.map((id) => MemberInfo(id,null,true))
.toList(growable: false)
);
}
RoomWithMemberInfos withInfo(MemberInfo info) {
return RoomWithMemberInfos(
chatroomid,infos
.map((e) => e.id == info.id ? MemberInfo(e.id,info.name,false) : e)
.toList(growable: false)
);
}
}
Stream<MemberInfo> getMemberInfo(int id) { ... }
getChatroomStream()
.switchMap((Room room) {
final initial = RoomWithMemberInfos.initial(room);
return Stream
.fromIterable(room.members)
.flatMap(getMemberInfo)
.scan<RoomWithMemberInfos>(
(acc,info) => acc!.withInfo(info),initial,)
.startWith(initial);
});