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