• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
<lambda>null2  * Copyright 2016-2021 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 kotlin.coroutines.*
10 
11 /**
12  * Creates cold [Completable] that runs a given [block] in a coroutine and emits its result.
13  * Every time the returned completable is subscribed, it starts a new coroutine.
14  * Unsubscribing cancels running coroutine.
15  * Coroutine context can be specified with [context] argument.
16  * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is used.
17  * Method throws [IllegalArgumentException] if provided [context] contains a [Job] instance.
18  */
19 public fun rxCompletable(
20     context: CoroutineContext = EmptyCoroutineContext,
21     block: suspend CoroutineScope.() -> Unit
22 ): Completable {
23     require(context[Job] === null) { "Completable context cannot contain job in it." +
24             "Its lifecycle should be managed via Disposable handle. Had $context" }
25     return rxCompletableInternal(GlobalScope, context, block)
26 }
27 
rxCompletableInternalnull28 private fun rxCompletableInternal(
29     scope: CoroutineScope, // support for legacy rxCompletable in scope
30     context: CoroutineContext,
31     block: suspend CoroutineScope.() -> Unit
32 ): Completable = Completable.create { subscriber ->
33     val newContext = scope.newCoroutineContext(context)
34     val coroutine = RxCompletableCoroutine(newContext, subscriber)
35     subscriber.setCancellable(RxCancellable(coroutine))
36     coroutine.start(CoroutineStart.DEFAULT, coroutine, block)
37 }
38 
39 private class RxCompletableCoroutine(
40     parentContext: CoroutineContext,
41     private val subscriber: CompletableEmitter
42 ) : AbstractCoroutine<Unit>(parentContext, false, true) {
onCompletednull43     override fun onCompleted(value: Unit) {
44         try {
45             subscriber.onComplete()
46         } catch (e: Throwable) {
47             handleUndeliverableException(e, context)
48         }
49     }
50 
onCancellednull51     override fun onCancelled(cause: Throwable, handled: Boolean) {
52         try {
53             if (subscriber.tryOnError(cause)) {
54                 return
55             }
56         } catch (e: Throwable) {
57             cause.addSuppressed(e)
58         }
59         handleUndeliverableException(cause, context)
60     }
61 }
62