在mobx存储中创建Firestore侦听器(颤振)

问题描述 投票:0回答:1

我目前正在使用Firestore和Mobx开发Flutter应用程序。我使用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个回答
0
投票

我没有使用颤动,但我想应该没什么不同。

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

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) => {
      const userUpdate = doc.data()
      if (userUpdate) {
        this.updateMyDetails(userUpdate)
      }
    })
  }

  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 (userUpdate),这是因为如果文档不存在,Firestore不会向您发送任何错误。 (如http 404)。您需要自己处理。

© www.soinside.com 2019 - 2024. All rights reserved.