gpt4 book ai didi

flutter - 使用 Cubit(BLoC 库)观察流?

转载 作者:行者123 更新时间:2023-12-04 13:29:25 37 4
gpt4 key购买 nike

TL;博士:有没有办法使用 Cubit 来监听流并发出状态而不是 BLoC ?
我正在使用 BLoC Flutter 库,我们使用 Cubit s 用于我们的状态管理。到目前为止,一切正常,用于获取数据或保存数据的交互,但现在我需要使用流。就我而言,这意味着观看来自 FirebaseFirestore 的快照.
我尝试在互联网上搜索是否有办法观察 Cubit 的流。而不是使用 BLoC但大部分结果都指向 BLoC .我曾与 BLoC 合作过在另一个项目中,所以我知道如何使用它来观察流,但我想使用 Cubit相反,如果有办法。
这是我用来在 FireStore 中观察的代码示例:

@override
Stream<Either<Failure, List<MTalk>>> watchTalk() async* {
const path ='path/to/talks';
yield* firestore
.collection(path)
.snapshots()
.map(
(snap) => right<Failure, List<MTalk>>(
snap.docs
.map(
(documentSnapshot) => MTalk.fromFirestore(documentSnapshot))
.toList(),
),
)
.onErrorReturnWith((e) {
if (e is FirestoreException) {
return left(RetrieveFailure(message: e.message));
} else {
return left(UnknownFailure(message: e.toString()));
}
});
}
}
使用时 BLoC ,你可以简单地使用 async*yield每当您从调用 watchTalk() 返回数据时返回状态因为 mapEventToState()也是一个产生 State 的流.在 Cubit的情况下,我们使用 emit(MyState)在 UI 中获取状态并且函数不是类型 Stream .我想知道的是我们是否可以使用 Cubit使用流。

最佳答案

如果有人像我一样感到困惑,那很简单。您可以在 cubit 上收听并在每次从流中获取值时发出状态。这是我使用 DataConnectionChecker 监听网络连接变化的代码示例:

///Listens to the connectivity of
Future<void> listenToConnectivity() async {
if (_internetStream != null) {
await _internetStream.cancel();
}
_internetStream = repo.isConnectedToInternet().listen((result) {
result.fold(
(failure) => _processFailure(failure: failure),
(isConnected) {
if (isConnected) {
emit(const SessionState.connected());
} else {
emit(const SessionState.disconnected());
}
},
);
});
}

关于flutter - 使用 Cubit(BLoC 库)观察流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66006767/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com