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 @file:Suppress("INVISIBLE_REFERENCE", "INVISIBLE_MEMBER")
6
7 package kotlinx.coroutines.rx2
8
9 import io.reactivex.*
10 import kotlinx.coroutines.*
11 import kotlinx.coroutines.channels.*
12 import kotlinx.coroutines.reactive.*
13 import kotlin.coroutines.*
14 import kotlin.internal.*
15
16 /**
17 * Creates cold [flowable][Flowable] that will run a given [block] in a coroutine.
18 * Every time the returned flowable is subscribed, it starts a new coroutine.
19 *
20 * Coroutine emits ([ObservableEmitter.onNext]) values with `send`, completes ([ObservableEmitter.onComplete])
21 * when the coroutine completes or channel is explicitly closed and emits error ([ObservableEmitter.onError])
22 * if coroutine throws an exception or closes channel with a cause.
23 * Unsubscribing cancels running coroutine.
24 *
25 * Invocations of `send` are suspended appropriately when subscribers apply back-pressure and to ensure that
26 * `onNext` is not invoked concurrently.
27 *
28 * Coroutine context can be specified with [context] argument.
29 * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is used.
30 * Method throws [IllegalArgumentException] if provided [context] contains a [Job] instance.
31 *
32 * **Note: This is an experimental api.** Behaviour of publishers that work as children in a parent scope with respect
33 */
34 @ExperimentalCoroutinesApi
rxFlowablenull35 public fun <T: Any> rxFlowable(
36 context: CoroutineContext = EmptyCoroutineContext,
37 @BuilderInference block: suspend ProducerScope<T>.() -> Unit
38 ): Flowable<T> {
39 require(context[Job] === null) { "Flowable context cannot contain job in it." +
40 "Its lifecycle should be managed via Disposable handle. Had $context" }
41 return Flowable.fromPublisher(publishInternal(GlobalScope, context, RX_HANDLER, block))
42 }
43
44 @Deprecated(
45 message = "CoroutineScope.rxFlowable is deprecated in favour of top-level rxFlowable",
46 level = DeprecationLevel.ERROR,
47 replaceWith = ReplaceWith("rxFlowable(context, block)")
48 ) // Since 1.3.0, will be error in 1.3.1 and hidden in 1.4.0
49 @LowPriorityInOverloadResolution
rxFlowablenull50 public fun <T: Any> CoroutineScope.rxFlowable(
51 context: CoroutineContext = EmptyCoroutineContext,
52 @BuilderInference block: suspend ProducerScope<T>.() -> Unit
53 ): Flowable<T> = Flowable.fromPublisher(publishInternal(this, context, RX_HANDLER, block))
54
55 private val RX_HANDLER: (Throwable, CoroutineContext) -> Unit = ::handleUndeliverableException
56