blob: a6a218cf46c6c4a92e8a01393d98505bdaedb9d0 [file] [log] [blame]
Vsevolod Tolstopyatovd57bfa22019-04-04 14:25:13 +03001/*
2 * Copyright 2016-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
3 */
4
5@file:JvmMultifileClass
6@file:JvmName("FlowKt")
7
8package kotlinx.coroutines.flow
9
10import kotlinx.coroutines.*
11import kotlin.jvm.*
12
13/**
14 * Terminal flow operator that collects the given flow with a provided [action].
15 * If any exception occurs during collect or in the provided flow, this exception is rethrown from this method.
16 *
17 * Example of use:
18 * ```
19 * val flow = getMyEvents()
20 * try {
Vsevolod Tolstopyatovd3cc25f2019-04-09 19:43:11 +030021 * flow.collect { value ->
22 * println("Received $value")
23 * }
24 * println("My events are consumed successfully")
Vsevolod Tolstopyatovd57bfa22019-04-04 14:25:13 +030025 * } catch (e: Throwable) {
Vsevolod Tolstopyatovd3cc25f2019-04-09 19:43:11 +030026 * println("Exception from the flow: $e")
Vsevolod Tolstopyatovd57bfa22019-04-04 14:25:13 +030027 * }
28 * ```
29 */
30@FlowPreview
Vsevolod Tolstopyatov641d6712019-04-29 17:13:57 +030031public suspend inline fun <T> Flow<T>.collect(crossinline action: suspend (value: T) -> Unit): Unit =
Vsevolod Tolstopyatovd57bfa22019-04-04 14:25:13 +030032 collect(object : FlowCollector<T> {
33 override suspend fun emit(value: T) = action(value)
34 })
Vsevolod Tolstopyatovd5478b62019-06-06 11:43:31 +030035
36/**
37 * Collects all the values from the given [flow] and emits them to the collector.
38 * Shortcut for `flow.collect { value -> emit(value) }`.
39 */
40public suspend inline fun <T> FlowCollector<T>.emitAll(flow: Flow<T>) = flow.collect(this)