1

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

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

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

4

1 回答 1

1

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

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);
        });
      }
    });
  }

}
于 2019-04-05T04:08:57.927 回答