如何在单个启动块(kotlin协程)中运行多个收集



是否有一些整洁的方式如何像launchAll,或collectAll(但不合并)?

好吧,就像这里的stackoverflow问题,或者这里在github导致我这个文档,onEach和launchIn的组合可能是首选的方式。

这是我的扩展,使它更清楚(关于收集):

/**
* 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
}

最新更新