我正在尝试将Amplify.DataStore.observeQuery
转换为存储库类中的流
期望的返回类型为Stream<List<MyObject>>
。
在存储库类中,您可以编写:
Stream<List<MyObject>> watchMessages() async* {
yield* Amplify.DataStore.observeQuery(MyObject.classType,
where: MyObject.ID.eq(myId))
.map((snapshot) => snapshot.items));
}
}
或者如果您必须将对象转换为域,则:
Stream<List<MyObject>> watchMessages() async* {
yield* Amplify.DataStore.observeQuery(MyObject.classType,
where: MyObject.ID.eq(myId))
.map((snapshot) => snapshot.items.map((e) => e.toDomain()).toList());
}
}
然后在区块中,您可以在每个流输入上发出状态:
MyBloc(this._repository) : super(MyState.initial()) {
on<_WatchMessages>((_onWatchMessages));
}
void _onWatchMessages(_WatchMessages event, Emitter<MyState> emit) async {
await emit.forEach(_repository.watchMessages(),
onData: ((List<MyObject> messages) {
return state.copyWith(messages: List.from(messages));
}));
}