collect

suspend fun Flow<*>.collect()

Terminal flow operator that collects the given flow but ignores all emitted values. If any exception occurs during collect or in the provided flow, this exception is rethrown from this method.

It is a shorthand for collect {}.

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

flow
.onEach { value -> process(value) }
.catch { e -> handleException(e) }
.collect() // trigger collection of the flow

inline suspend fun <T> Flow<T>.collect(crossinline action: suspend (T) -> Unit)

Terminal flow operator that collects the given flow with a provided action. If any exception occurs during collect or in the provided flow, this exception is rethrown from this method.

Example of use:

val flow = getMyEvents()
try {
flow.collect { value ->
println("Received $value")
}
println("My events are consumed successfully")
} catch (e: Throwable) {
println("Exception from the flow: $e")
}

inline suspend fun <T> SharedFlow<T>.collect(crossinline action: suspend (T) -> Unit): Nothing

Terminal flow operator that collects the given SharedFlow with the provided action. If any exception occurs during collect or in the provided flow, this exception is rethrown from this method.

This is a counterpart of a regular Flow.collect extension, only different in the return type so that any code below collect produces a compilation warning.