Search code examples
androidkotlinkotlin-flow

Androi Kotlin flow: How to call multiple task in sequence without many callback


I have 2 flows (flow1, flow2) and want to call 2 flows in sequential (flow1 then flow2) because "flow2" depend on "flow1" result but want to implement "flow1" based on condition.

val flow1 = flow<Int> {
        emit(1) // start loading
        delay(200) // getting data from net.
        emit(200) // get data
        emit(1) // stop loading
    }
    val flow2: (Int)-> Flow<String> = {
        flow<String> {
            emit("$it,1") // start loading
            delay(200) // getting data from net.
            emit("$it,200") // get data
            emit("$it,1") // stop loading
        }
    }

-something like that: flow1.checkCondition(somecondition where if it was false, it will not implement "flow1") .someOperator(flow2) // this is some operator that takes "flow2" .collect {} // receive "flow2" result

-note: -how to do it with on collect function that receives "flow2" result. -I know that there are other ways but I want to know what operator is used for that kind code. - If there are not some operators that can't do that code, suggest a way that make code more flat without many inner callbacks.


Solution

  • Function flatMapLatest may be what you need. It returns a flow that switches to a new flow produced by transform function every time the original flow (flow1) emits a value. When the original flow emits a new value, the previous flow produced by transform block is cancelled:

    viewModelScope.launch {
        flow1.flatMapLatest { flow2(it) }.collect { flow2Result: String ->
            // use flow2Result
        }
    }
    

    where viewModelScope is a scope available in ViewModel, it can be any other instance of CoroutineScope.