collect

suspend fun Flow<*>.collect(): Unit (source)

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 (value: T) -> Unit
): Unit
(source)

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")
}