Skip to content

Flows: Combining

Devrath edited this page Jan 20, 2024 · 1 revision

Where Combine operator can be useful

It is the same as zip in combining the two flows, But Once one of the flow emission is available, The other flow users that to combine instead of waiting for two flows.

Output

Result:-> xx
Result:-> xy
Result:-> xz
Result:-> yz
Result:-> zz
Time Taken:-> 5021

Code

    private val flowCombineOne = flow {
        emit("x")
        delay(5000)
        emit("y")
        emit("z")
    }.flowOn(Dispatchers.Default)

    private val flowCombineTwo = flow {
        emit("x")
        emit("y")
        emit("z")
    }.flowOn(Dispatchers.Default)

    fun combining() = viewModelScope.launch{
        // It will show the time taken to execute this block of code
        val time = measureTimeMillis {
            flowCombineOne.combine(flowCombineTwo){ one , two ->
                one+two
            }.collect{
                println("Result:-> $it")
            }
        }
        println("Time Taken:-> $time")
    }
Clone this wiki locally