【发布时间】:2019-08-22 21:43:29
【问题描述】:
我希望能够在我的 ViewModel 中使用 Kotlin 协程来收听 Firebase DB 中的实时更新。
问题在于,每当在集合中创建新消息时,我的应用程序都会冻结并且无法从该状态中恢复。我需要杀死它并重新启动应用程序。
这是第一次通过,我可以在 UI 上看到之前的消息。第二次调用SnapshotListener 时会出现此问题。
我的observer() 函数
val channel = Channel<List<MessageEntity>>()
firestore.collection(path).addSnapshotListener { data, error ->
if (error != null) {
channel.close(error)
} else {
if (data != null) {
val messages = data.toObjects(MessageEntity::class.java)
//till this point it gets executed^^^^
channel.sendBlocking(messages)
} else {
channel.close(CancellationException("No data received"))
}
}
}
return channel
这就是我想要观察消息的方式
launch(Dispatchers.IO) {
val newMessages =
messageRepository
.observer()
.receive()
}
}
在我用send() 替换sendBlocking() 之后,我仍然没有在频道中收到任何新消息。 SnapshotListener方被执行
//channel.sendBlocking(messages) was replaced by code bellow
scope.launch(Dispatchers.IO) {
channel.send(messages)
}
//scope is my viewModel
如何使用 Kotlin 协程观察 firestore/realtime-dbs 中的消息?
【问题讨论】:
-
Firebase 回调默认在主线程上执行。我看到你在主线程上调用了一个名为
sendBlocking的方法。阻塞主线程总是一个坏主意。您需要找到另一种使用 Firebase SDK 的方法,而不是像这样阻塞主线程。 -
@DougStevenson 我找到了解决方案
标签: android kotlin google-cloud-firestore kotlin-coroutines