• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download

<lambda>null1 @file:Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
2 
3 package kotlinx.coroutines.reactor
4 
5 import kotlinx.coroutines.*
6 import kotlinx.coroutines.reactive.*
7 import org.reactivestreams.*
8 import reactor.core.*
9 import reactor.core.publisher.*
10 import kotlin.coroutines.*
11 import kotlinx.coroutines.internal.*
12 
13 /**
14  * Creates a cold [mono][Mono] that runs a given [block] in a coroutine and emits its result.
15  * Every time the returned mono is subscribed, it starts a new coroutine.
16  * If the result of [block] is `null`, [MonoSink.success] is invoked without a value.
17  * Unsubscribing cancels the running coroutine.
18  *
19  * Coroutine context can be specified with [context] argument.
20  * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is used.
21  *
22  * @throws IllegalArgumentException if the provided [context] contains a [Job] instance.
23  */
24 public fun <T> mono(
25     context: CoroutineContext = EmptyCoroutineContext,
26     block: suspend CoroutineScope.() -> T?
27 ): Mono<T> {
28     require(context[Job] === null) { "Mono context cannot contain job in it." +
29             "Its lifecycle should be managed via Disposable handle. Had $context" }
30     return monoInternal(GlobalScope, context, block)
31 }
32 
33 /**
34  * Awaits the single value from the given [Mono] without blocking the thread and returns the resulting value, or, if
35  * this publisher has produced an error, throws the corresponding exception. If the Mono completed without a value,
36  * `null` is returned.
37  *
38  * This suspending function is cancellable.
39  * If the [Job] of the current coroutine is cancelled while the suspending function is waiting, this
40  * function immediately cancels its [Subscription] and resumes with [CancellationException].
41  */
awaitSingleOrNullnull42 public suspend fun <T> Mono<T>.awaitSingleOrNull(): T? = suspendCancellableCoroutine { cont ->
43     injectCoroutineContext(cont.context).subscribe(object : Subscriber<T> {
44         private var value: T? = null
45 
46         override fun onSubscribe(s: Subscription) {
47             cont.invokeOnCancellation { s.cancel() }
48             s.request(Long.MAX_VALUE)
49         }
50 
51         override fun onComplete() {
52             cont.resume(value)
53             value = null
54         }
55 
56         override fun onNext(t: T) {
57             // We don't return the value immediately because the process that emitted it may not be finished yet.
58             // Resuming now could lead to race conditions between emitter and the awaiting code.
59             value = t
60         }
61 
62         override fun onError(error: Throwable) { cont.resumeWithException(error) }
63     })
64 }
65 
66 /**
67  * Awaits the single value from the given [Mono] without blocking the thread and returns the resulting value, or,
68  * if this Mono has produced an error, throws the corresponding exception.
69  *
70  * This suspending function is cancellable.
71  * If the [Job] of the current coroutine is cancelled while the suspending function is waiting, this
72  * function immediately cancels its [Subscription] and resumes with [CancellationException].
73  *
74  * @throws NoSuchElementException if the Mono does not emit any value
75  */
76 // TODO: consider using https://github.com/Kotlin/kotlinx.coroutines/issues/2607 once that lands
awaitSinglenull77 public suspend fun <T> Mono<T>.awaitSingle(): T = awaitSingleOrNull() ?: throw NoSuchElementException()
78 
79 private fun <T> monoInternal(
80     scope: CoroutineScope, // support for legacy mono in scope
81     context: CoroutineContext,
82     block: suspend CoroutineScope.() -> T?
83 ): Mono<T> = Mono.create { sink ->
84     val reactorContext = context.extendReactorContext(sink.currentContext())
85     val newContext = scope.newCoroutineContext(context + reactorContext)
86     val coroutine = MonoCoroutine(newContext, sink)
87     sink.onDispose(coroutine)
88     coroutine.start(CoroutineStart.DEFAULT, coroutine, block)
89 }
90 
91 private class MonoCoroutine<in T>(
92     parentContext: CoroutineContext,
93     private val sink: MonoSink<T>
94 ) : AbstractCoroutine<T>(parentContext, false, true), Disposable {
95     @Volatile
96     private var disposed = false
97 
onCompletednull98     override fun onCompleted(value: T) {
99         if (value == null) sink.success() else sink.success(value)
100     }
101 
onCancellednull102     override fun onCancelled(cause: Throwable, handled: Boolean) {
103         /** Cancellation exceptions that were caused by [dispose], that is, came from downstream, are not errors. */
104         val unwrappedCause = unwrap(cause)
105         if (getCancellationException() !== unwrappedCause || !disposed) {
106             try {
107                 /** If [sink] turns out to already be in a terminal state, this exception will be passed through the
108                  * [Hooks.onOperatorError] hook, which is the way to signal undeliverable exceptions in Reactor. */
109                 sink.error(cause)
110             } catch (e: Throwable) {
111                 // In case of improper error implementation or fatal exceptions
112                 cause.addSuppressed(e)
113                 handleCoroutineException(context, cause)
114             }
115         }
116     }
117 
disposenull118     override fun dispose() {
119         disposed = true
120         cancel()
121     }
122 
isDisposednull123     override fun isDisposed(): Boolean = disposed
124 }
125 
126 /**
127  * @suppress
128  */
129 @Deprecated(
130     message = "CoroutineScope.mono is deprecated in favour of top-level mono",
131     level = DeprecationLevel.HIDDEN,
132     replaceWith = ReplaceWith("mono(context, block)")
133 ) // Since 1.3.0, will be error in 1.3.1 and hidden in 1.4.0
134 public fun <T> CoroutineScope.mono(
135     context: CoroutineContext = EmptyCoroutineContext,
136     block: suspend CoroutineScope.() -> T?
137 ): Mono<T> = monoInternal(this, context, block)
138 
139 /**
140  * This is a lint function that was added already deprecated in order to guard against confusing usages on [Mono].
141  * On [Publisher] instances other than [Mono], this function is not deprecated.
142  *
143  * Both [awaitFirst] and [awaitSingle] await the first value, or throw [NoSuchElementException] if there is none, but
144  * the name [Mono.awaitSingle] better reflects the semantics of [Mono].
145  *
146  * For example, consider this code:
147  * ```
148  * myDbClient.findById(uniqueId).awaitFirst() // findById returns a `Mono`
149  * ```
150  * It looks like more than one value could be returned from `findById` and [awaitFirst] discards the extra elements,
151  * when in fact, at most a single value can be present.
152  *
153  * @suppress
154  */
155 @Deprecated(
156     message = "Mono produces at most one value, so the semantics of dropping the remaining elements are not useful. " +
157         "Please use awaitSingle() instead.",
158     level = DeprecationLevel.HIDDEN,
159     replaceWith = ReplaceWith("this.awaitSingle()")
160 ) // Warning since 1.5, error in 1.6
161 public suspend fun <T> Mono<T>.awaitFirst(): T = awaitSingle()
162 
163 /**
164  * This is a lint function that was added already deprecated in order to guard against confusing usages on [Mono].
165  * On [Publisher] instances other than [Mono], this function is not deprecated.
166  *
167  * Both [awaitFirstOrDefault] and [awaitSingleOrNull] await the first value, or return some special value if there
168  * is none, but the name [Mono.awaitSingleOrNull] better reflects the semantics of [Mono].
169  *
170  * For example, consider this code:
171  * ```
172  * myDbClient.findById(uniqueId).awaitFirstOrDefault(default) // findById returns a `Mono`
173  * ```
174  * It looks like more than one value could be returned from `findById` and [awaitFirstOrDefault] discards the extra
175  * elements, when in fact, at most a single value can be present.
176  *
177  * @suppress
178  */
179 @Deprecated(
180     message = "Mono produces at most one value, so the semantics of dropping the remaining elements are not useful. " +
181         "Please use awaitSingleOrNull() instead.",
182     level = DeprecationLevel.HIDDEN,
183     replaceWith = ReplaceWith("this.awaitSingleOrNull() ?: default")
184 ) // Warning since 1.5, error in 1.6
185 public suspend fun <T> Mono<T>.awaitFirstOrDefault(default: T): T = awaitSingleOrNull() ?: default
186 
187 /**
188  * This is a lint function that was added already deprecated in order to guard against confusing usages on [Mono].
189  * On [Publisher] instances other than [Mono], this function is not deprecated.
190  *
191  * Both [awaitFirstOrNull] and [awaitSingleOrNull] await the first value, or return some special value if there
192  * is none, but the name [Mono.awaitSingleOrNull] better reflects the semantics of [Mono].
193  *
194  * For example, consider this code:
195  * ```
196  * myDbClient.findById(uniqueId).awaitFirstOrNull() // findById returns a `Mono`
197  * ```
198  * It looks like more than one value could be returned from `findById` and [awaitFirstOrNull] discards the extra
199  * elements, when in fact, at most a single value can be present.
200  *
201  * @suppress
202  */
203 @Deprecated(
204     message = "Mono produces at most one value, so the semantics of dropping the remaining elements are not useful. " +
205         "Please use awaitSingleOrNull() instead.",
206     level = DeprecationLevel.HIDDEN,
207     replaceWith = ReplaceWith("this.awaitSingleOrNull()")
208 ) // Warning since 1.5, error in 1.6
209 public suspend fun <T> Mono<T>.awaitFirstOrNull(): T? = awaitSingleOrNull()
210 
211 /**
212  * This is a lint function that was added already deprecated in order to guard against confusing usages on [Mono].
213  * On [Publisher] instances other than [Mono], this function is not deprecated.
214  *
215  * Both [awaitFirstOrElse] and [awaitSingleOrNull] await the first value, or return some special value if there
216  * is none, but the name [Mono.awaitSingleOrNull] better reflects the semantics of [Mono].
217  *
218  * For example, consider this code:
219  * ```
220  * myDbClient.findById(uniqueId).awaitFirstOrElse(defaultValue) // findById returns a `Mono`
221  * ```
222  * It looks like more than one value could be returned from `findById` and [awaitFirstOrElse] discards the extra
223  * elements, when in fact, at most a single value can be present.
224  *
225  * @suppress
226  */
227 @Deprecated(
228     message = "Mono produces at most one value, so the semantics of dropping the remaining elements are not useful. " +
229         "Please use awaitSingleOrNull() instead.",
230     level = DeprecationLevel.HIDDEN,
231     replaceWith = ReplaceWith("this.awaitSingleOrNull() ?: defaultValue()")
232 ) // Warning since 1.5, error in 1.6
233 public suspend fun <T> Mono<T>.awaitFirstOrElse(defaultValue: () -> T): T = awaitSingleOrNull() ?: defaultValue()
234 
235 /**
236  * This is a lint function that was added already deprecated in order to guard against confusing usages on [Mono].
237  * On [Publisher] instances other than [Mono], this function is not deprecated.
238  *
239  * Both [awaitLast] and [awaitSingle] await the single value, or throw [NoSuchElementException] if there is none, but
240  * the name [Mono.awaitSingle] better reflects the semantics of [Mono].
241  *
242  * For example, consider this code:
243  * ```
244  * myDbClient.findById(uniqueId).awaitLast() // findById returns a `Mono`
245  * ```
246  * It looks like more than one value could be returned from `findById` and [awaitLast] discards the initial elements,
247  * when in fact, at most a single value can be present.
248  *
249  * @suppress
250  */
251 @Deprecated(
252     message = "Mono produces at most one value, so the last element is the same as the first. " +
253         "Please use awaitSingle() instead.",
254     level = DeprecationLevel.HIDDEN,
255     replaceWith = ReplaceWith("this.awaitSingle()")
256 ) // Warning since 1.5, error in 1.6
257 public suspend fun <T> Mono<T>.awaitLast(): T = awaitSingle()
258