如何从不同的函数中发出流量值? Kotlin协程 [英] How to emit Flow value from different function? Kotlin Coroutines

查看:129
本文介绍了如何从不同的函数中发出流量值? Kotlin协程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个流程:

val myflow = kotlinx.coroutines.flow.flow<Message>{}

并希望使用以下函数发出值:

and want to emit values with function:

override suspend fun sendMessage(chat: Chat, message: Message) {
    myflow.emit(message)
}

但是编译器不允许我这样做,是否有任何解决方法来解决此问题?

But compiler does not allow me to do this, is there any workarounds to solve this problem?

推荐答案

Animesh Sahu的答案非常正确.您还可以返回渠道作为流(请参见 consumeAsFlow asFlow

The answer of Animesh Sahu is pretty much correct. You can also return a Channel as a flow (see consumeAsFlow or asFlow on a BroadcastChannel).

但是还有一个叫做 StateFlow 的东西正在开发中由Kotlin团队提供,部分目的是实现类似的行为,尽管尚不清楚何时准备就绪.

But there is also a thing called StateFlow currently in development by Kotlin team, which is, in part, meant to implement a similar behavior, although it is unknown when it is going to be ready.

这篇关于如何从不同的函数中发出流量值? Kotlin协程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆