'How to run multiple collects in single launch block (kotlin coroutines)
Is there some neat way how do something like launchAll, or collectAll (but not merge)?
Solution 1:[1]
Well, just like this stackoverflow question here or here in github which lead me to this documentation, combination of onEach and launchIn is probably preferred way.
There is my extension to make it more clear (about collecting):
/**
* Collects given receiver flow in given scope.
*
* Replaces several launch blocks with single collect call.
*
* Simplify onEach{ block() }.launchIn(coroutineScope).
*/
fun <T> Flow<T>.collectIn(scope: CoroutineScope, context: CoroutineContext = EmptyCoroutineContext, action: suspend (T) -> Unit): Job =
onEach(action).launchIn(scope, context)
/**
* Collect.kt variant of [launchIn] with ability to specify context to launch in.
*/
fun <T> Flow<T>.launchIn(scope: CoroutineScope, context: CoroutineContext = EmptyCoroutineContext): Job = scope.launch(context) {
collect() // tail-call
}
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 | ThinkDeep |
