Home > OS >  combine(Flow...) is not working with 3 Flows
combine(Flow...) is not working with 3 Flows

Time:10-31

I'm trying to use combine() to combine 3 flows but nothing happens. This is my code:

combine(flowX, flowY, flowZ) { x, y, z ->
    println("$x, $y, $z") // this line is never reached
}

I know my flows are good because this works:

val x = flowX.first()
val y = flowY.first()
val z = flowZ.first()

println("$x, $y, $z") // this line is executed and prints the right values

Why would my flows emit with first() but not combine()?

CodePudding user response:

combine() is not a terminal flow operator. It only creates a new flow and returns it, but it doesn't start collecting the flow. You still need to collect the flow to actually start executing it:

combine(flowX, flowY, flowZ) { x, y, z ->
    println("$x, $y, $z")
}.collect {}

This solution seems a little strange to me, as it prints in the lambda that was supposed to transform the value, then it returns a flow of Unit and collects doing nothing. Alternatively, you can do it this way:

combine(flowX, flowY, flowZ) { x, y, z -> Triple(x, y, z) }
    .collect { (x, y, z) -> println("$x, $y, $z") }
  • Related