我希望能够在我的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?

推荐答案

我最终得到的是我使用的Flow,它是协程1.2.0-alpha-2的一部分

return flowViaChannel { channel ->
   firestore.collection(path).addSnapshotListener { data, error ->
        if (error != null) {
            channel.close(error)
        } else {
            if (data != null) {
                val messages = data.toObjects(MessageEntity::class.java)
                channel.sendBlocking(messages)
            } else {
                channel.close(CancellationException("No data received"))
            }
        }
    }
    channel.invokeOnClose {
        it?.printStackTrace()
    }
} 

And that's how I observe it in my ViewModel

launch {
    messageRepository.observe().collect {
        //process
    }
}

更多话题https://medium.com/@elizarov/cold-flows-hot-channels-d74769805f9

Kotlin相关问答推荐

Kotlin-删除按钮周围的空格

在Kotlin项目中使用Free Fair AspectJ插件(使用Gradle)

Kotlin中反射中Int到可空Double的隐式转换失败

Kotlin 复制列表中的项目以创建具有相同数据的不同对象的新列表

如何使用成员引用在 Kotlin 中创建属性的分层路径

正则表达式 FindAll 不打印结果 Kotlin

如何在kotlin中使用协程每秒调用一个函数

Kotlin 插件错误:无法为类 org.jetbrains.kotlin.gradle.tasks.KotlinCompile 生成代理类

Kotlin 和 Java 字符串拆分与正则表达式的区别

无法从 XML 访问 NavHostFragment

jetpack compose 将参数传递给 viewModel

Map.mapTo 到另一个map

创建首选项屏幕时找不到androidx.preference.PreferenceScreen

如何在主线程上使用 Kotlin 协程 await()

TextField maxLength - Android Jetpack Compose

Kotlin:什么是 kotlin.String!类型

应用程序在使用 Google Play 服务时遇到问题

如何让数据类在Kotlin中实现接口/扩展超类属性?

Kotlin Flow 收集后无法执行代码

Kotlin:在何时使用枚举