'Androi Kotlin flow: How to call multiple task in sequence without many callback
i have 2 flow (flow1, flow2) and want to call 2 flows in sequential (flow1 then flow2) cause "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 receive "flow2" result. -i know that there is another ways but i want to know what operator is used for that kind code. - if there is not some operators that can't do that code, suggest a way that make code more flat without many inner callbacks.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | BigSt |
