Computer scienceProgramming languagesKotlinConcurrency and parallelismConcurrency

SharedFlow

Real-time message broadcasting in chat

Report a typo

In a Kotlin-based chat application, you are tasked with implementing a feature that allows any message sent by a user to be seen and displayed in real-time by all other users. The solution should use a mechanism that supports multiple collectors and allows multiple coroutines to emit values. Your current challenge is to complete the provided code snippet to ensure that the feature enables sending and receiving values through a flow that can be shared simultaneously across different coroutines.

Fill in the gaps with the relevant elements
import kotlinx.coroutines.flow.
import kotlinx.coroutines.flow.
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.launch

fun main() = runBlocking {
    val sharedFlow = MutableSharedFlow<String>()
    launch {
        sharedFlow.collect { value -> println(value) }
    }
    launch {
        sharedFlow.("Hello")
        sharedFlow.emit("SharedFlow")
    }
}
___

Create a free account to access the full topic