【问题标题】:How to init a second stream depending on events from the first stream?如何根据第一个流中的事件启动第二个流?
【发布时间】:2019-08-24 15:30:13
【问题描述】:

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

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

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

【问题讨论】:

  • 从您的 BLoC 中,您只想公开一个 MyPageModel 流?还是您也想公开身份验证状态?
  • 仅限 MyPageModel。如果用户未登录,则将 userSignedIn 设置为 false,在其他情况下 userSignedIn = true 并填充 privateData
  • 谢谢,工作正常。您能否发表评论作为回复。我会检查它作为解决方案。

标签: dart flutter rxdart


【解决方案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);
        });
      }
    });
  }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-05
    • 2021-09-18
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多