How to emit Flow value from different function? Kotlin Coroutines

You can use StateFlow or SharedFlow APIs for such use case.
Here’s a sample code with the usage of StateFlow.

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>

Leave a Comment

tech