HomeAndroidKotlin Move - Mix, Merge and Zip

Kotlin Move – Mix, Merge and Zip


That is a part of the asynchronous stream collection:

I’ve 2 flows right here.

Flow1 emits int ranging from 1 -> 1000 each 1 second.

non-public val flow1: Move<Int> = stream {
    repeat(10000) { worth ->
        delay(1000)
        Log.d(tag, "[Flow1]: emitting $worth")
        emit(worth)
    }
}

Move 2 emits char from A to Z each 2 seconds.

non-public val flow2: Move<Char> = stream {
    var worth = 'A'
    whereas(true) {
        delay(2000)
        Log.d(tag, "[Flow2]: emitting $worth")
        emit(worth)
        if (worth == 'Z') {
            worth = 'A'
        } else {
            worth += 1
        }
    }
}

Mix

This combines flow1 and flow2 into combineFlow utilizing the Move.mix() extension perform stream operator.

val combineFlow = flow1.mix(flow2) { flow1Value,flow2Value  ->
    "${flow1Value}_${flow2Value}"
}

The limitation of this Move.mix() extension perform is it’s restricted to combining 2 flows. To mix greater than 2 flows, you should use mix() perform instantly which helps as much as 5 flows.

val combineFlow = mix(flow1, flow2) { flow1Value, flow2Value ->
    "${flow1Value}_${flow2Value}"
}

To gather the stream, I take advantage of the LaunchedEffect() facet impact for this demonstration objective. The really helpful method is both utilizing collectAsStateWithLifeCylce()or repeatOnLifecycle(Lifecycle.State.STARTED), see right here.

LaunchedEffect(true) {
    viewModel.combineFlow.accumulate { worth ->
        Log.d(tag, "[Combine Flow]: $worth")
    }
}

So that is the output. It combines the newest worth from flow1 and flow2.

Merge

This merges flow1 and flow2 into mergeFlow,

val mergeFlow = merge(flow1, flow2)

and right here is the output:

1 and A are emitted on the similar time, adopted by 2, then 3 and B and so forth.

Zip

This zips flow1 and flow2 into zipFlow,

val zipFlow = flow1.zip(flow2) { flow1value,flow2value  ->
    "${flow1value}_${flow2value}"
}

and right here is the output:

As you possibly can see from this output, Zip pairs up the information from flow1 and flow2.

Conclusion

The above diagrams assist me to know the distinction between mix, merge and zip stream operators.

I’ve been utilizing mix() on this mission right here which mixes the stream from a ROOM database(articles) with one other stream from a Proto DataStore(consumer settings). I would not have any probability to make use of Merge() and Zip(). 🙂

Supply Code

GitHub Repository: Demo_AsyncFlow (see the CombineMergeZipFlowActivity)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments