【问题标题】:Creating Firestore Listeners in a mobx store (flutter)在 mobx 商店中创建 Firestore 监听器(颤振)
【发布时间】:2020-05-12 09:18:19
【问题描述】:

我目前正在开发一个使用 firestore 和 mobx 的颤振应用程序。我使用 mobx 使 UI 保持最新,并对 firestore 进行 api 调用(因此数据流是 firestore -> mobx store -> UI)。我想设置监听器来监听 firestore 集合中的实时变化。理想情况下,我想在 mobx 中设置这个监听器,但我不确定这将如何工作 - mobx 商店是监听 Firestore 更改的正确位置吗?我担心的一件事是 mobx 商店中没有可以分离侦听器的 dispose 方法。我想知道这是否是一种可接受的方式来更新我的商店中的变量(以及间接更新 UI),或者我是否需要切换到 BLoC/流模型。任何有关此问题的一般建议(即侦听实时 Firestore 更新并将更改传播到 UI 的最佳方式)将不胜感激!

【问题讨论】:

    标签: flutter mobile google-cloud-firestore mobx bloc


    【解决方案1】:

    我没有使用颤振,但我想应该不会有太大的不同。

    这是我如何在我的应用中监听用户配置文件更改的示例。

    class UserModel {
      @observable id = ''
    
      updateDetails (userUpdate) {
        // update observable properties
      }
    
      destroy () {
        // Call destroy to remove listener
        if (this.stopWatch) {
          this.stopWatch()
        }
      }
    
      init () {
        // firestore onSnapshot returns a disposer, keep it on the instance
        this.stopWatch = fdb.collection('users').doc(this.id).onSnapshot((doc) => {
          if (doc.exists) {
            this.updateMyDetails(doc.data())
          }
        })
      }
    
      constructor ({id}) {
        // ...
        this.id = id
      }
    }
    
    const user = new UserModel({id: 'firestoreId')})
    user.init()
    
    // then any observer, like your UI, is listening to changes of the userModel data
    
    //...
    
    user.destroy() // for example when the user signs out.
    

    请注意,如果您想将这些关注点分开,而不是使用此 init 函数,则可以在模型之外监听更改。

    如果您想知道我为什么要检查if (doc.exists),那是因为如果文档不存在,Firestore 不会向您发送任何错误。 (如 http 404)。你需要自己处理。

    【讨论】:

    • 如何在整个反应应用程序中访问用户存储。我将如何注入等。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2023-03-25
    • 2017-11-24
    • 2021-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多