gpt4 book ai didi

dart - 如何根据第一个流中的事件初始化第二个流?

转载 作者:IT王子 更新时间:2023-10-29 06:57:36 25 4
gpt4 key购买 nike

在我的 BLOC 中,我需要监听 FirebaseAuth.instance.onAuthStateChanged 并且根据用户 uid 将初始化第二个流 Firestore.instance.collection('accounts/${uid}/private').snapshots() 并将结果合并到一个模型中:

    class MyPageModel {
bool userSignedIn;
List<String> privateData;
}

这个模型需要用BehaviorSubject流出。使用 rxdart 完成此任务的最佳方法是什么?

最佳答案

检查下面的代码,了解如何组合两个条件流:

class TheBLoC{
BehaviorSubject<MyPageModel> _userDataSubject = BehaviorSubject<MyPageModel>();
// use this in your StreamBuilder widget
Stream<MyPageModel> get userData => _userDataSubject.stream;
// a reference to the stream of the user's private data
StreamSubscription<QuerySnapshot> _subscription;
// bool with the state of the user so we make sure we don't show any data
// unless the user is currently loggedin.
bool isUserLoggedIn;

TheBLoC() {
isUserLoggedIn = false;
FirebaseAuth.instance.onAuthStateChanged.listen((firebaseUser) {
if (firebaseUser.isAnonymous()) {
isUserLoggedIn = false;
final event = MyPageModel();
event.isSignedIn = false;
_userDataSubject.add(event);
// cancel the previous _subscription if available
_subscription?.cancel();
// should also probably nullify the _subscription reference
} else {
isUserLoggedIn = true;
// the user is logged in so acces his's data
_subscription = Firestore.instance.collection
('accounts/${firebaseUser.uid}/private')
.snapshots().listen((querySnapshots){
if(!isUserLoggedIn) return;
final event = MyPageModel();
event.isSignedIn = true;
// use the querySnapshots to initialize the privateData in
// MyPageModel
_userDataSubject.add(event);
});
}
});
}

}

关于dart - 如何根据第一个流中的事件初始化第二个流?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55489452/

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