launchIn

fun <T> Flow<T>.launchIn(scope: CoroutineScope): Job

Terminal flow operator that launches the collection of the given flow in the scope. It is a shorthand for scope.launch { flow.collect() }.

This operator is usually used with onEach, onCompletion and catch operators to process all emitted values handle an exception that might occur in the upstream flow or during processing, for example:

flow
.onEach { value -> updateUi(value) }
.onCompletion { cause -> updateUi(if (cause == null) "Done" else "Failed") }
.catch { cause -> LOG.error("Exception: $cause") }
.launchIn(uiScope)

Note that the resulting value of launchIn is not used and the provided scope takes care of cancellation.

Sources

common source
Link copied to clipboard