Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ScopeProvider.coroutineScope: Deliver lifecycle exceptions to CoroutineExceptionHandler instead of throwing at call-site. #632

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion android/gradle/libs.versions.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ javapoet = "1.11.1"
jsr250 = "1.0"
junit = "4.12"
kotlin = "1.8.20"
kotlinx-coroutines = "1.7.3"
kotlinx-coroutines = "1.8.0-RC2"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is now 1.9.0-RC

ktfmt = "0.43"
ktlint = "0.48.2"
leakcanary = "1.5.4"
Expand Down
2 changes: 2 additions & 0 deletions android/libraries/rib-coroutines/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ dependencies {
api(libs.autodispose.coroutines)
api(libs.coroutines.android)
api(libs.coroutines.rx2)
implementation(libs.autodispose.lifecycle)

compileOnly(libs.android.api)

testImplementation(project(":libraries:rib-base"))
testImplementation(project(":libraries:rib-test"))
testImplementation(project(":libraries:rib-coroutines-test"))
testImplementation(testLibs.junit)
testImplementation(testLibs.mockito)
testImplementation(testLibs.mockitoKotlin)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,23 @@
package com.uber.rib.core

import android.app.Application
import com.uber.autodispose.OutsideScopeException
import com.uber.autodispose.ScopeProvider
import com.uber.autodispose.coroutinesinterop.asCoroutineScope
import com.uber.rib.core.internal.CoroutinesFriendModuleApi
import com.uber.rib.core.internal.DirectDispatcher
import java.util.WeakHashMap
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.reflect.KProperty
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import kotlinx.coroutines.job
import kotlinx.coroutines.launch
import kotlinx.coroutines.rx2.await

/**
* [CoroutineScope] tied to this [ScopeProvider]. This scope will be canceled when ScopeProvider is
Expand All @@ -37,15 +43,7 @@ import kotlinx.coroutines.job
*/
@OptIn(CoroutinesFriendModuleApi::class)
public val ScopeProvider.coroutineScope: CoroutineScope by
LazyCoroutineScope<ScopeProvider> {
val context: CoroutineContext =
SupervisorJob() +
RibDispatchers.Main.immediate +
CoroutineName("${this::class.simpleName}:coroutineScope") +
(RibCoroutinesConfig.exceptionHandler ?: EmptyCoroutineContext)

asCoroutineScope(context)
}
LazyCoroutineScope<ScopeProvider> { ScopeProviderCoroutineScope(this, createCoroutineContext()) }

/**
* [CoroutineScope] tied to this [Application]. This scope will not be cancelled, it lives for the
Expand All @@ -56,15 +54,40 @@ public val ScopeProvider.coroutineScope: CoroutineScope by
*/
@OptIn(CoroutinesFriendModuleApi::class)
public val Application.coroutineScope: CoroutineScope by
LazyCoroutineScope<Application> {
val context: CoroutineContext =
SupervisorJob() +
RibDispatchers.Main.immediate +
CoroutineName("${this::class.simpleName}:coroutineScope") +
(RibCoroutinesConfig.exceptionHandler ?: EmptyCoroutineContext)
LazyCoroutineScope<Application> { CoroutineScope(createCoroutineContext()) }

private fun Any.createCoroutineContext() =
SupervisorJob() +
RibDispatchers.Main.immediate +
CoroutineName("${this::class.simpleName}:coroutineScope") +
(RibCoroutinesConfig.exceptionHandler ?: EmptyCoroutineContext)

CoroutineScope(context)
private class ScopeProviderCoroutineScope(
scopeProvider: ScopeProvider,
override val coroutineContext: CoroutineContext,
) : ScopeProvider by scopeProvider, CoroutineScope {
init {
requireNotNull(coroutineContext[Job]) { "coroutineContext must have a job in it" }
cancelWhenLifecycleEnded()
}
}

@OptIn(CoroutinesFriendModuleApi::class)
private fun ScopeProviderCoroutineScope.cancelWhenLifecycleEnded() {
launch(DirectDispatcher, CoroutineStart.UNDISPATCHED) { awaitCompletion() }
.invokeOnCompletion { e -> cancel("Lifecycle is not active", e) }
}

private suspend inline fun ScopeProvider.awaitCompletion() {
try {
requestScope().await()
} catch (e: OutsideScopeException) {
throw CoroutineScopeLifecycleException(
message = "Attempted to obtain ScopeProvider.coroutineScope out of lifecycle bounds",
cause = e,
)
}
}

@CoroutinesFriendModuleApi
public class LazyCoroutineScope<This : Any>(private val initializer: This.() -> CoroutineScope) {
Expand All @@ -88,3 +111,9 @@ public class LazyCoroutineScope<This : Any>(private val initializer: This.() ->
}
}
}

public class CoroutineScopeLifecycleException
internal constructor(
message: String,
cause: OutsideScopeException,
) : RuntimeException(message, cause)
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 a risk 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()
}
}
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)
}
Loading