How to emit Flow value from different function? Kotlin Coroutines

拥有回忆 提交于 2020-08-09 02:41:56

问题


I have a flow :

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?


回答1:


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

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.




回答2:


Flow is self contained, once the block (lambda) inside the flow is executed the flow is over, you've to do operations inside and emit them from there.

Here is the similar github issue, says:

Afaik Flow is designed to be a self contained, replayable, cold stream, so emission from outside of it's own scope wouldn't be part of the contract. I think what you're looking for is a Channel.

And IMHO you're probably looking at the Channels, or specifically a ConflatedBroadcastChannel for multiple receivers. The difference between a normal channel and a broadcast channel is that multiple receivers can listen to a broadcast channel using openSubscription function which returns a ReceiveChannel associated with the BroadcastChannel.




回答3:


You can use StateFlow for such use case. Here's a sample code.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

val chatFlow = MutableStateFlow<String>("")

fun main() = runBlocking {

    // Observe values
    val job = launch {
        chatFlow.collect {
            print("$it ")
        }
    }

    // Change values
    arrayOf("Hey", "Hi", "Hello").forEach {
        delay(100)
        sendMessage(it)
    }

    delay(1000)

    // Cancel running job
    job.cancel()
    job.join()
}

suspend fun sendMessage(message: String) {
    chatFlow.value = message
}

You can test this code by running below snippet.

<iframe src="https://pl.kotl.in/DUBDfUnX3" style="width:600px;"></iframe>


来源:https://stackoverflow.com/questions/61655136/how-to-emit-flow-value-from-different-function-kotlin-coroutines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!