-
Notifications
You must be signed in to change notification settings - Fork 22
Flattening Flow: FlatMapMerge or FlattenMerge
Devrath edited this page Jan 23, 2024
·
2 revisions
When there is a flow of flows and we want the value from the inner flow, We can use the flattenConcat
operator
Also the flatMapConcat
is a combination of map + flattenMerge
Output
<Emitted> -->0
Current string no -->0 at the threadDefaultDispatcher-worker-2
<Emitted> -->1
Current string no -->1 at the threadDefaultDispatcher-worker-2
<Emitted> -->2
Current string no -->2 at the threadDefaultDispatcher-worker-2
<Emitted> -->3
Current string no -->3 at the threadDefaultDispatcher-worker-2
<Emitted> -->4
Current string no -->4 at the threadDefaultDispatcher-worker-3
Code
class FlattenFlowsDemoVm @Inject constructor(
@ApplicationContext private val context: Context,
) : ViewModel() {
private val rootScope = CoroutineScope(context = Dispatchers.IO)
/**
* Flow of integers
*/
fun generateIntegers() = flow {
repeat(100){
delay(1000)
emit(it)
}
}
/**
* Generate a flow of strings
*/
fun generateFlowOfStrings(value : Int) = flow {
val content = "Current string no -->$value at the thread${Thread.currentThread().name}"
println("<Emitted> -->$value")
emit(content)
}
fun flatMapMerge() = rootScope.launch(CoroutineName("flatMapMerge")){
generateIntegers()
.take(5)
.flatMapMerge() {
generateFlowOfStrings(it)
}.collect{
println(it)
}
}
}