|
| 1 | +/* |
| 2 | + * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
| 3 | + */ |
| 4 | + |
| 5 | +package kotlinx.coroutines.jdk9 |
| 6 | + |
| 7 | +import kotlinx.coroutines.CancellationException |
| 8 | +import kotlinx.coroutines.Job |
| 9 | +import kotlinx.coroutines.suspendCancellableCoroutine |
| 10 | +import java.util.concurrent.Flow.Publisher |
| 11 | +import java.util.concurrent.Flow.Subscriber |
| 12 | +import java.util.concurrent.Flow.Subscription |
| 13 | +import java.util.* |
| 14 | +import kotlin.coroutines.* |
| 15 | + |
| 16 | +/** |
| 17 | + * Awaits for the first value from the given publisher without blocking a thread and |
| 18 | + * returns the resulting value or throws the corresponding exception if this publisher had produced error. |
| 19 | + * |
| 20 | + * This suspending function is cancellable. |
| 21 | + * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function |
| 22 | + * immediately resumes with [CancellationException]. |
| 23 | + * |
| 24 | + * @throws NoSuchElementException if publisher does not emit any value |
| 25 | + */ |
| 26 | +public suspend fun <T> Publisher<T>.awaitFirst(): T = awaitOne(Mode.FIRST) |
| 27 | + |
| 28 | +/** |
| 29 | + * Awaits for the first value from the given observable or the [default] value if none is emitted without blocking a |
| 30 | + * thread and returns the resulting value or throws the corresponding exception if this observable had produced error. |
| 31 | + * |
| 32 | + * This suspending function is cancellable. |
| 33 | + * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function |
| 34 | + * immediately resumes with [CancellationException]. |
| 35 | + */ |
| 36 | +public suspend fun <T> Publisher<T>.awaitFirstOrDefault(default: T): T = awaitOne(Mode.FIRST_OR_DEFAULT, default) |
| 37 | + |
| 38 | +/** |
| 39 | + * Awaits for the first value from the given observable or `null` value if none is emitted without blocking a |
| 40 | + * thread and returns the resulting value or throws the corresponding exception if this observable had produced error. |
| 41 | + * |
| 42 | + * This suspending function is cancellable. |
| 43 | + * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function |
| 44 | + * immediately resumes with [CancellationException]. |
| 45 | + */ |
| 46 | +public suspend fun <T> Publisher<T>.awaitFirstOrNull(): T? = awaitOne(Mode.FIRST_OR_DEFAULT) |
| 47 | + |
| 48 | +/** |
| 49 | + * Awaits for the first value from the given observable or call [defaultValue] to get a value if none is emitted without blocking a |
| 50 | + * thread and returns the resulting value or throws the corresponding exception if this observable had produced error. |
| 51 | + * |
| 52 | + * This suspending function is cancellable. |
| 53 | + * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function |
| 54 | + * immediately resumes with [CancellationException]. |
| 55 | + */ |
| 56 | +public suspend fun <T> Publisher<T>.awaitFirstOrElse(defaultValue: () -> T): T = awaitOne(Mode.FIRST_OR_DEFAULT) ?: defaultValue() |
| 57 | + |
| 58 | +/** |
| 59 | + * Awaits for the last value from the given publisher without blocking a thread and |
| 60 | + * returns the resulting value or throws the corresponding exception if this publisher had produced error. |
| 61 | + * |
| 62 | + * This suspending function is cancellable. |
| 63 | + * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function |
| 64 | + * immediately resumes with [CancellationException]. |
| 65 | + * |
| 66 | + * @throws NoSuchElementException if publisher does not emit any value |
| 67 | + */ |
| 68 | +public suspend fun <T> Publisher<T>.awaitLast(): T = awaitOne(Mode.LAST) |
| 69 | + |
| 70 | +/** |
| 71 | + * Awaits for the single value from the given publisher without blocking a thread and |
| 72 | + * returns the resulting value or throws the corresponding exception if this publisher had produced error. |
| 73 | + * |
| 74 | + * This suspending function is cancellable. |
| 75 | + * If the [Job] of the current coroutine is cancelled or completed while this suspending function is waiting, this function |
| 76 | + * immediately resumes with [CancellationException]. |
| 77 | + * |
| 78 | + * @throws NoSuchElementException if publisher does not emit any value |
| 79 | + * @throws IllegalArgumentException if publisher emits more than one value |
| 80 | + */ |
| 81 | +public suspend fun <T> Publisher<T>.awaitSingle(): T = awaitOne(Mode.SINGLE) |
| 82 | + |
| 83 | +// ------------------------ private ------------------------ |
| 84 | + |
| 85 | +// ContextInjector service is implemented in `kotlinx-coroutines-reactor` module only. |
| 86 | +// If `kotlinx-coroutines-reactor` module is not included, the list is empty. |
| 87 | +private val contextInjectors: Array<ContextInjector> = |
| 88 | + ServiceLoader.load(ContextInjector::class.java, ContextInjector::class.java.classLoader).iterator().asSequence().toList().toTypedArray() // R8 opto |
| 89 | + |
| 90 | +private fun <T> Publisher<T>.injectCoroutineContext(coroutineContext: CoroutineContext) = |
| 91 | + contextInjectors.fold(this) { pub, contextInjector -> |
| 92 | + contextInjector.injectCoroutineContext(pub, coroutineContext) |
| 93 | + } |
| 94 | + |
| 95 | +private enum class Mode(val s: String) { |
| 96 | + FIRST("awaitFirst"), |
| 97 | + FIRST_OR_DEFAULT("awaitFirstOrDefault"), |
| 98 | + LAST("awaitLast"), |
| 99 | + SINGLE("awaitSingle"); |
| 100 | + override fun toString(): String = s |
| 101 | +} |
| 102 | + |
| 103 | +private suspend fun <T> Publisher<T>.awaitOne( |
| 104 | + mode: Mode, |
| 105 | + default: T? = null |
| 106 | +): T = suspendCancellableCoroutine { cont -> |
| 107 | + injectCoroutineContext(cont.context).subscribe(object : Subscriber<T> { |
| 108 | + private lateinit var subscription: Subscription |
| 109 | + private var value: T? = null |
| 110 | + private var seenValue = false |
| 111 | + |
| 112 | + override fun onSubscribe(sub: Subscription) { |
| 113 | + subscription = sub |
| 114 | + cont.invokeOnCancellation { sub.cancel() } |
| 115 | + sub.request(if (mode == Mode.FIRST) 1 else Long.MAX_VALUE) |
| 116 | + } |
| 117 | + |
| 118 | + override fun onNext(t: T) { |
| 119 | + when (mode) { |
| 120 | + Mode.FIRST, Mode.FIRST_OR_DEFAULT -> { |
| 121 | + if (!seenValue) { |
| 122 | + seenValue = true |
| 123 | + subscription.cancel() |
| 124 | + cont.resume(t) |
| 125 | + } |
| 126 | + } |
| 127 | + Mode.LAST, Mode.SINGLE -> { |
| 128 | + if (mode == Mode.SINGLE && seenValue) { |
| 129 | + subscription.cancel() |
| 130 | + if (cont.isActive) |
| 131 | + cont.resumeWithException(IllegalArgumentException("More than one onNext value for $mode")) |
| 132 | + } else { |
| 133 | + value = t |
| 134 | + seenValue = true |
| 135 | + } |
| 136 | + } |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + @Suppress("UNCHECKED_CAST") |
| 141 | + override fun onComplete() { |
| 142 | + if (seenValue) { |
| 143 | + if (cont.isActive) cont.resume(value as T) |
| 144 | + return |
| 145 | + } |
| 146 | + when { |
| 147 | + mode == Mode.FIRST_OR_DEFAULT -> { |
| 148 | + cont.resume(default as T) |
| 149 | + } |
| 150 | + cont.isActive -> { |
| 151 | + cont.resumeWithException(NoSuchElementException("No value received via onNext for $mode")) |
| 152 | + } |
| 153 | + } |
| 154 | + } |
| 155 | + |
| 156 | + override fun onError(e: Throwable) { |
| 157 | + cont.resumeWithException(e) |
| 158 | + } |
| 159 | + }) |
| 160 | +} |
| 161 | + |
0 commit comments