Skip to content

Flows: Zipping

Devrath edited this page Jan 20, 2024 · 3 revisions

Where ZIP operator can be useful

  • It is useful when you can combine 2 flows of emissions into one emission just like a zip sales the two paths to one
  • ZIP collect triggers when both values change

Output

Result:-> xx
Result:-> yy
Result:-> zz
Time Taken:-> 42

Code

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

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

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