How to init a second stream depending on events from the first stream?


In my BLOC I need to listen to FirebaseAuth.instance.onAuthStateChanged and depending on users uid will init second stream Firestore.instance.collection('accounts/${uid}/private').snapshots() and combine results to one model:

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

This model need to be streamed out with BehaviorSubject. What is best approach using rxdart for this task?


Check the code below to see how you may combine the two conditional streams:

class TheBLoC{
  BehaviorSubject<MyPageModel> _userDataSubject = BehaviorSubject<MyPageModel>();
  // use this in your StreamBuilder widget
  Stream<MyPageModel> get userData =>;
  // 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;
        // cancel the previous _subscription if available
        // should also probably nullify the _subscription reference 
      } else {
        isUserLoggedIn = true;
        // the user is logged in so acces his's data
        _subscription = Firestore.instance.collection
              if(!isUserLoggedIn) return;
              final event = MyPageModel();              
              event.isSignedIn = true;
              // use the querySnapshots to initialize the privateData in 
              // MyPageModel


Answered By – user

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *