我希望能够在我的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
That's how I want to observe messages
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
How to observe messages in firestore/realtime-dbs using Kotlin coroutines?