在我的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/

10-09 04:21