-
Notifications
You must be signed in to change notification settings - Fork 906
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Change
ScopeProvider.coroutineScope
throwing behavior when accessin…
…g it before scope is active, or after scope is inactive. Instead of throwing at call site, we deliver `CoroutineScopeLifecycleException(message: String, cause: OutsideScopeException)` to the `CoroutineExceptionHandler` installed at `RibCoroutinesConfig.exceptionHandler`. Note `cause` is always non-null, and it's either `LifecycleNotStartedException` or `LifecycleEndedException`. ## Motivation Suppose you have an interactor that starts subscribing to an Rx stream asynchronously. ```kotlin class MyInteractor { override fun didBecomeActive() { runLater { someObservable.autoDispose(this).subscribe() } } } ``` It is possible that this Rx subscription will be triggered after interactor's already inactive. In that case, subscription will be No-Op. This is not good code for a major reason: `Interactor` is attempting to do work after it's inactive. In other words, `runLater` does not respect the interactor lifecycle. Still, considering this is some legacy code being migrated from Rx to Coroutines, the new code would look like the following. ```kotlin class MyInteractor { override fun didBecomeActive() { runLater { someObservable.autoDispose(coroutineScope).subscribe() } } } ``` Unlike the Rx counterpart, this code will sometimes fatally throw. If `ScopeProvider.coroutineScope` is called after the scope's inactive, it will throw `LifecycleEndedException` at call site. Calling `coroutineScope` outside of lifecycle bounds is always erroneous code. But in order to favour a smoother migration to Coroutines, and to avoid surprises of `val` throwing exceptions, we are changing current implementation to deliver the exception to the `CoroutineExceptionHandler` instead of throwing at call site. If some app decides to override the default behavior of crashing (in JVM/Android) in face of this erroneous code, one can customize `RibCoroutinesConfig.exceptionHandler` at app startup: ```kotlin RibCoroutinesConfig.exceptionHandler = CoroutineExceptionHandler { _, throwable -> when (throwable) { is CoroutineScopeLifecycleException -> log(throwable) // only log, don't re-throw. else -> throw throwable } } ```
- Loading branch information
Showing
5 changed files
with
213 additions
and
19 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
39 changes: 39 additions & 0 deletions
39
...d/libraries/rib-coroutines/src/main/kotlin/com/uber/rib/core/internal/DirectDispatcher.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
/* | ||
* Copyright (C) 2024. Uber Technologies | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package com.uber.rib.core.internal | ||
|
||
import kotlin.coroutines.CoroutineContext | ||
import kotlinx.coroutines.CoroutineDispatcher | ||
import kotlinx.coroutines.Runnable | ||
|
||
/** | ||
* A coroutine dispatcher that is not confined to any specific thread. It executes the initial | ||
* continuation of a coroutine in the current call-frame and lets the coroutine resume in whatever | ||
* thread that is used by the corresponding suspending function, without mandating any specific | ||
* threading policy. | ||
* | ||
* This dispatcher is similar to [Unconfined][com.uber.rib.core.RibDispatchers.Unconfined], with the | ||
* difference that it does not form an event-loop on nested coroutines, which implies that it has | ||
* predictable ordering of events with the tradeoff of an increased risk of [StackOverflowError]. | ||
* | ||
* **This is internal API, not supposed to be used by library consumers.** | ||
*/ | ||
@CoroutinesFriendModuleApi | ||
public object DirectDispatcher : CoroutineDispatcher() { | ||
override fun dispatch(context: CoroutineContext, block: Runnable) { | ||
block.run() | ||
} | ||
} |
124 changes: 124 additions & 0 deletions
124
android/libraries/rib-coroutines/src/test/kotlin/com/uber/rib/core/RibCoroutineScopesTest.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,124 @@ | ||
/* | ||
* Copyright (C) 2024. Uber Technologies | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package com.uber.rib.core | ||
|
||
import com.google.common.truth.Truth.assertThat | ||
import com.uber.autodispose.lifecycle.LifecycleEndedException | ||
import com.uber.autodispose.lifecycle.LifecycleNotStartedException | ||
import kotlin.contracts.ExperimentalContracts | ||
import kotlin.contracts.InvocationKind | ||
import kotlin.contracts.contract | ||
import kotlinx.coroutines.CoroutineExceptionHandler | ||
import kotlinx.coroutines.ExperimentalCoroutinesApi | ||
import kotlinx.coroutines.Job | ||
import kotlinx.coroutines.awaitCancellation | ||
import kotlinx.coroutines.isActive | ||
import kotlinx.coroutines.launch | ||
import kotlinx.coroutines.test.runCurrent | ||
import kotlinx.coroutines.test.runTest | ||
import org.hamcrest.CoreMatchers.instanceOf | ||
import org.junit.Before | ||
import org.junit.Rule | ||
import org.junit.Test | ||
import org.junit.rules.ExpectedException | ||
import org.junit.runner.RunWith | ||
import org.junit.runners.Parameterized | ||
import org.mockito.kotlin.mock | ||
|
||
@OptIn(ExperimentalCoroutinesApi::class) | ||
@RunWith(Parameterized::class) | ||
class RibCoroutineScopesTest( | ||
private val throwWhenBeforeActive: Boolean, | ||
private val throwWhenAfterInactive: Boolean, | ||
) { | ||
@get:Rule val ribCoroutinesRule = RibCoroutinesRule() | ||
|
||
@get:Rule val exceptionRule: ExpectedException = ExpectedException.none() | ||
|
||
private val interactor = TestInteractor() | ||
|
||
@Before | ||
fun setUp() { | ||
RibCoroutinesConfig.exceptionHandler = CoroutineExceptionHandler { _, throwable -> | ||
when (throwable) { | ||
is CoroutineScopeLifecycleException -> if (shouldThrow(throwable)) throw throwable | ||
else -> throw throwable | ||
} | ||
} | ||
} | ||
|
||
@Test | ||
fun coroutineScope_whenCalledBeforeActive_throwsCoroutineScopeLifecycleException() = runTest { | ||
if (throwWhenBeforeActive) { | ||
exceptionRule.expect(CoroutineScopeLifecycleException::class.java) | ||
exceptionRule.expectCause(instanceOf(LifecycleNotStartedException::class.java)) | ||
} | ||
assertThat(interactor.coroutineScope.isActive).isFalse() | ||
} | ||
|
||
@Test | ||
fun coroutineScope_whenCalledAfterInactive_throwsCoroutineScopeLifecycleException() = runTest { | ||
if (throwWhenAfterInactive) { | ||
exceptionRule.expect(CoroutineScopeLifecycleException::class.java) | ||
exceptionRule.expectCause(instanceOf(LifecycleEndedException::class.java)) | ||
} | ||
interactor.attachAndDetach {} | ||
assertThat(interactor.coroutineScope.isActive).isFalse() | ||
} | ||
|
||
@Test | ||
fun coroutineScope_whenCalledWhileActive_cancelsWhenInactive() = runTest { | ||
var launched = false | ||
val job: Job | ||
interactor.attachAndDetach { | ||
job = | ||
coroutineScope.launch { | ||
launched = true | ||
awaitCancellation() | ||
} | ||
runCurrent() | ||
assertThat(launched).isTrue() | ||
assertThat(job.isActive).isTrue() | ||
} | ||
assertThat(job.isCancelled).isTrue() | ||
} | ||
|
||
private fun shouldThrow(e: CoroutineScopeLifecycleException): Boolean = | ||
(throwWhenBeforeActive && e.cause is LifecycleNotStartedException) || | ||
(throwWhenAfterInactive && e.cause is LifecycleEndedException) | ||
|
||
companion object { | ||
@JvmStatic | ||
@Parameterized.Parameters(name = "throwWhenBeforeActive = {0}, throwWhenAfterInactive = {1}") | ||
fun data() = | ||
listOf( | ||
arrayOf(true, true), | ||
arrayOf(true, false), | ||
arrayOf(false, true), | ||
arrayOf(false, false), | ||
) | ||
} | ||
} | ||
|
||
private class TestInteractor : Interactor<Unit, Router<*>>() | ||
|
||
@OptIn(ExperimentalContracts::class) | ||
private inline fun TestInteractor.attachAndDetach(block: TestInteractor.() -> Unit) { | ||
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) } | ||
InteractorHelper.attach(this, Unit, mock(), null) | ||
block() | ||
InteractorHelper.detach(this) | ||
} |