Home > Net >  Kotlin coroutines: How to flatMapConcat 3 flows, if one of them has not started emitting yet?
Kotlin coroutines: How to flatMapConcat 3 flows, if one of them has not started emitting yet?

Time:09-22

I have 3 flows:

val flow1 = ... // emits values from the app start
val flow2 = ... // emits values from the app start
val flow3 = someBooleanFlow.flatMapLatest{ if(it) flowOf(42) else emptyFlow() } // emits when user registered

I need:

val state = flow1.flatMapConcat{ value1 ->
        flow2.flatMapConcat{ value2 -> 
     flow3.flatMapConcat{ value3 -> when{ ... } // so value3 is not received if flow3 is empty, 
// but I need its default value here to perform "when" logics
       }
    }
}

The question is how to take a default value in flatMapConcat when one of flows has not emitted? The issue is also valid for combine

CodePudding user response:

You can use onStart on a Flow to emit an initial value:

val flowWithInitialValue = sourceFlow.onStart { emit(initialValue) }

You could also use a StateFlow for this, and provide your initial value at construction time.

I'm guessing flow3 represents some kind of user ID for the logged in user.

In this case, I would not use an emptyFlow() to represent the non-logged case. You can probably use a nullable user ID or a sealed class as element of your flow, so you can emit null or UserLoginStatus.Anonymous as a first default value.

  • Related