launchIn

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

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 resulting value of launchIn is not used the provided scope takes care of cancellation.