launchInSafely

Launches the collection of this flow in scope, routing any upstream failure to onError instead of letting it propagate to (and cancel) the parent scope.

It is catch { error -> if (error is CancellationException) throw error else onError(error) } .launchIn(scope). The catch operator only handles exceptions thrown by the upstream. Any CancellationException is rethrown, so cancelling scope or the returned Job does not invoke onError. Values emitted before a failure are still delivered downstream. Exceptions thrown by onError itself propagate normally.

Example:

repository.getItems()
.map { it.toUiModel() }
.onEach { _state.value = it }
.launchInSafely(viewModelScope) { e -> _error.value = e.message }

Rules: FLOW_005 (missing catch in a Flow chain). See docs/BEST_PRACTICES_COROUTINES.md section 9.6.

Requires opting in to ExperimentalStructuredCoroutines.

Receiver

the upstream flow to collect.

Return

the Job of the launched collection.

Parameters

scope

the scope in which collection is launched; the returned job is its child.

onError

invoked with any non-cancellation upstream failure. It is not invoked for any CancellationException.

See also