我有个 idea :

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)
}

但是编译器不允许我这样做,有什么解决方法可以解决这个问题吗?

推荐答案

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).

但是,Kotlin团队目前正在开发一个名为StateFlow的东西,它在一定程度上是为了实现类似的行为,尽管它什么时候能准备好还不得而知.

EDIT: StateFlow and SharedFlow have been released as part of a stable API (https://blog.jetbrains.com/kotlin/2020/10/kotlinx-coroutines-1-4-0-introducing-stateflow-and-sharedflow/). These tools can and should be used when state management is required in an async execution context.

Kotlin相关问答推荐

如何在不基于数据 map 的情况下将图例添加到lets plot kotlin

禁用 Gradle执行消息

如何让 LocalDateTime.parse 拒绝 24:00 时间

使用 kotlin 流删除 map 中具有某些相似性的值

mutableStateOf 和 mutableStateListOf 有什么区别?

Kotlin中用于调用常量名称的枚举类方法之间的区别

错误:cannot find symbol import com.gourav.news.databinding.ActivityDetailBindingImpl;

interface扩展

Kotlin 方法重载

Kotlin 协程中的 Dispatchers.Main 和 Dispatchers.Default 有什么区别?

将 @Component.Builder 与构造函数参数一起使用

片段内的 Kotlin 按钮 onClickListener 事件

将 Android Studio 升级到 3.1.0 后的 Android Support 插件错误

Firestore - 如何在 Kotlin 中排除数据类对象的字段

Kotlin Android:属性委托必须有一个 'getValue(DashViewModel, KProperty*>)' 方法

旋转 kotlin 数组

lateinit 的 isInitialized 属性在伴随对象中不起作用

递归方法调用在 kotlin 中导致 StackOverFlowError 但在 java 中没有

Kotlin 对象 vs 伴生对象(companion-object) vs 包作用域(package scoped)方法

java.lang.NoClassDefFoundError:解析失败:Lkotlin/time/MonoClock