Skip to content

Flattening Flow: FlatMapMerge or FlattenMerge

Devrath edited this page Jan 23, 2024 · 2 revisions

When to use flattenMerge or flatMapMerge

When there is a flow of flows and we want the value from the inner flow, We can use the flattenConcat operator

What is FlatMapMerge

Also the flatMapConcat is a combination of map + flattenMerge

Thread on which it is used

Observe it uses different co-routines to run async-synchronously together

Output

<Emitted> -->0
Current string no -->0 at the threadDefaultDispatcher-worker-2
<Emitted> -->1
Current string no -->1 at the threadDefaultDispatcher-worker-2
<Emitted> -->2
Current string no -->2 at the threadDefaultDispatcher-worker-2
<Emitted> -->3
Current string no -->3 at the threadDefaultDispatcher-worker-2
<Emitted> -->4
Current string no -->4 at the threadDefaultDispatcher-worker-3

Code

class FlattenFlowsDemoVm @Inject constructor(
    @ApplicationContext private val context: Context,
) : ViewModel() {

    private val rootScope = CoroutineScope(context = Dispatchers.IO)

    /**
     * Flow of integers
     */
    fun generateIntegers() = flow {
        repeat(100){
            delay(1000)
            emit(it)
        }
    }


    /**
     * Generate a flow of strings
     */
    fun generateFlowOfStrings(value : Int) = flow {
        val content = "Current string no -->$value at the thread${Thread.currentThread().name}"
        println("<Emitted> -->$value")
        emit(content)
    }



    fun flatMapMerge() = rootScope.launch(CoroutineName("flatMapMerge")){

        generateIntegers()
            .take(5)
            .flatMapMerge() {
                generateFlowOfStrings(it)
            }.collect{
                println(it)
            }

    }

}
Clone this wiki locally