Vsevolod Tolstopyatov | d57bfa2 | 2019-04-04 14:25:13 +0300 | [diff] [blame] | 1 | /* |
| 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 | |
| 8 | package kotlinx.coroutines.flow |
| 9 | |
| 10 | import kotlinx.coroutines.* |
| 11 | import 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 Tolstopyatov | d3cc25f | 2019-04-09 19:43:11 +0300 | [diff] [blame] | 21 | * flow.collect { value -> |
| 22 | * println("Received $value") |
| 23 | * } |
| 24 | * println("My events are consumed successfully") |
Vsevolod Tolstopyatov | d57bfa2 | 2019-04-04 14:25:13 +0300 | [diff] [blame] | 25 | * } catch (e: Throwable) { |
Vsevolod Tolstopyatov | d3cc25f | 2019-04-09 19:43:11 +0300 | [diff] [blame] | 26 | * println("Exception from the flow: $e") |
Vsevolod Tolstopyatov | d57bfa2 | 2019-04-04 14:25:13 +0300 | [diff] [blame] | 27 | * } |
| 28 | * ``` |
| 29 | */ |
| 30 | @FlowPreview |
Vsevolod Tolstopyatov | 641d671 | 2019-04-29 17:13:57 +0300 | [diff] [blame] | 31 | public suspend inline fun <T> Flow<T>.collect(crossinline action: suspend (value: T) -> Unit): Unit = |
Vsevolod Tolstopyatov | d57bfa2 | 2019-04-04 14:25:13 +0300 | [diff] [blame] | 32 | collect(object : FlowCollector<T> { |
| 33 | override suspend fun emit(value: T) = action(value) |
| 34 | }) |
Vsevolod Tolstopyatov | d5478b6 | 2019-06-06 11:43:31 +0300 | [diff] [blame^] | 35 | |
| 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 | */ |
| 40 | public suspend inline fun <T> FlowCollector<T>.emitAll(flow: Flow<T>) = flow.collect(this) |