我有个 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)
}
但是编译器不允许我这样做,有什么解决方法可以解决这个问题吗?
我有个 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.