ios - EnvironmentObject is not notifying changes to views that are subscribed
问题描述
I have this app where I am implementing a logout feature with firebase firestore. What I want to do is detach all my snapshotListeners when the user logs out. I use an environmentObject to observe when the user logged out.
class StatusManager: ObservableObject{
@Published var didLogOut: Bool = false
}
I inject the object into the environment. Then, I catch the object in every view that has a listener.
@EnvironmentObject var statusManager: StatusManager
This is how I plan to detach the listener once the user logs out.
.onAppear(perform: {
if statusManager.didLogOut == false{
notifyListener = db.collectionGroup("resources").whereField("control", isEqualTo: true).addSnapshotListener { (snapshot, err) in
//All the functionality
}
}
else{
notifyListener?.remove()
}
})
And this is where the user logs out.
Button(action: {
isLoggedIn = false
lastLoggedEmail = ""
lastLoggedUserType = ""
lastLoggedUserPassword = ""
statusManager.didLogOut = true
try? Auth.auth().signOut()
navStack.pop(to: .root)
}, label: {
Text("Sign Out")
.font(Font.custom("Roboto-Light", size: 14))
})
The problem is, The code where I use the snapshot listener is never reread once the didLogOut state is changed. Therefore, the snapshot listener is never removed.
解决方案
If the view where your notifyListener logic is not re-drawn (as in removed from the tree and re-added again) that code will only run once (when it's shown for the first time, since it's an onAppear block). If that's the case you can use the onChange block instead.
.onChange(of: statusManager.didLogOut) { value
if value == false {
notifyListener = db.collectionGroup("resources").whereField("control", isEqualTo: true).addSnapshotListener { (snapshot, err) in }
} else {
notifyListener?.remove()
}
})
推荐阅读
- r - 找不到函数
- php - 当我在我的本地主机系统上安装 apache2 时,它显示了这个错误(Ubuntu 17.10)
- arangodb - Arngodb,Arangojs 检索数据时出错
- javascript - React - 循环内循环
- azure - 如何为应用程序网关后面托管的站点显示“停机维护”
- node.js - 我在哪里可以在 Node.js 中使用 mongoose 创建 MongoDB 文档?
- c++ - 具有回溯和 DP 的不同输出
- php - 将 PHP 片段放在另一个单引号变量中
- javascript - 为什么我对 Printful API 的请求被拒绝访问?
- php - 使用 with() 从 laravel 中的 DB 中仅选择必填字段