From c7a9d7b4ae8aaf5da5b939950070e7cddd7299a3 Mon Sep 17 00:00:00 2001 From: Yangcy Zhang <807528013@qq.com> Date: Fri, 18 Sep 2026 00:40:27 +0800 Subject: [PATCH 1/4] Fix coroutine cancellation propagation --- README.md | 2 +- .../yangcyzhang/coroutinekit/ext/FlowExt.kt | 26 ++++++++++++----- .../coroutinekit/ext/SuspendExt.kt | 8 ++--- .../coroutinekit/utils/DispatcherUtils.kt | 2 +- .../coroutinekit/ext/FlowExtTest.kt | 29 +++++++++++++++++++ .../coroutinekit/ext/SuspendExtTest.kt | 19 ++++++++++++ 6 files changed, 71 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 8984034..b1ef145 100644 --- a/README.md +++ b/README.md @@ -115,7 +115,7 @@ val future: CompletableFuture = suspendToFuture { ### 8. Java Interop — Callback → Flow ```kotlin -val sensorFlow: Flow = callbackFlow( +val sensorFlow: Flow = callbackToFlow( register = { onResult, onError -> sensorManager.register(object : SensorListener { override fun onData(d: SensorData) = onResult(d) diff --git a/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/ext/FlowExt.kt b/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/ext/FlowExt.kt index 2dcf8d6..b7af4b9 100644 --- a/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/ext/FlowExt.kt +++ b/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/ext/FlowExt.kt @@ -1,10 +1,10 @@ package com.yangcyzhang.coroutinekit.ext +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow -import kotlinx.coroutines.flow.catch -import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flatMapLatest +import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.flow.retryWhen @@ -102,7 +102,8 @@ fun Flow.retryWithDelay( * Executes [action] on each emitted value without cancelling the Flow on exception. * * Unlike [onEach], if the [action] throws, the exception is caught and the Flow - * continues processing subsequent items. This is useful for safe logging, + * continues processing subsequent items. [CancellationException] is always re-thrown. + * This is useful for safe logging, * analytics, or side-effect operations that should not affect the main data stream. * * Example: @@ -121,15 +122,20 @@ fun Flow.retryWithDelay( */ fun Flow.onEachCatching(action: suspend (T) -> Unit): Flow = onEach { value -> - runCatching { action(value) } - // Exceptions from action are intentionally swallowed here. - // CancellationException from the outer scope will still propagate normally. + try { + action(value) + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + // Exceptions from action are intentionally swallowed here. + } } /** * A variant of [flatMapLatest] that catches and ignores exceptions thrown * inside the [transform] block. When an exception occurs, no value is emitted - * for that particular input and the flow continues normally. + * for that particular input and the flow continues normally. [CancellationException] + * is always re-thrown. * * @param transform a function to transform each upstream value into a new Flow * @return a Flow applying flatMapLatest with exception suppression @@ -142,6 +148,8 @@ fun Flow.flatMapLatestCatching( ): Flow = flatMapLatest { value -> try { transform(value) + } catch (e: CancellationException) { + throw e } catch (e: Exception) { flow { /* emit nothing on error */ } } @@ -150,7 +158,7 @@ fun Flow.flatMapLatestCatching( /** * Maps each upstream value using [transform], filtering out both null results * and any exceptions thrown. Equivalent to combining [mapNotNull] with - * safe exception handling. + * safe exception handling. [CancellationException] is always re-thrown. * * @param transform a suspending transform that may return null or throw * @return a Flow of non-null successfully transformed values @@ -162,6 +170,8 @@ fun Flow.mapNotNullCatching( ): Flow = transform { value -> try { transform(value)?.let { emit(it) } + } catch (e: CancellationException) { + throw e } catch (_: Exception) { // Skip items that fail transformation } diff --git a/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/ext/SuspendExt.kt b/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/ext/SuspendExt.kt index e1de2ae..834572d 100644 --- a/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/ext/SuspendExt.kt +++ b/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/ext/SuspendExt.kt @@ -3,6 +3,7 @@ package com.yangcyzhang.coroutinekit.ext import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job +import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeout @@ -49,6 +50,7 @@ suspend fun suspendRunCatching(block: suspend () -> T): Result = try { /** * Executes the given [block] within the specified timeout. If the timeout is exceeded, * returns [defaultValue] instead of throwing [kotlinx.coroutines.TimeoutCancellationException]. + * Cancellation initiated by an outer coroutine scope is always propagated. * * This is a safer alternative to [withTimeout] when a fallback value is preferred * over an exception-based control flow. @@ -73,11 +75,7 @@ suspend fun withTimeoutOrDefault( block: suspend CoroutineScope.() -> T ): T = try { withTimeout(timeMillis, block) -} catch (e: CancellationException) { - // withTimeout throws TimeoutCancellationException which IS-A CancellationException. - // We only want to catch the timeout case, not an outer scope cancellation. - // TimeoutCancellationException has a specific message we can check, but the safest - // approach in production is to return defaultValue for any cancellation here. +} catch (_: TimeoutCancellationException) { defaultValue } diff --git a/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/utils/DispatcherUtils.kt b/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/utils/DispatcherUtils.kt index be889ea..f07e58f 100644 --- a/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/utils/DispatcherUtils.kt +++ b/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/utils/DispatcherUtils.kt @@ -38,7 +38,7 @@ object CoroutineKitDispatchers { /** * Dispatcher for main thread / UI operations. - * Defaults to [Dispatchers.Main]. + * Defaults to [Dispatchers.Default] because this artifact also supports plain JVM. */ var main: CoroutineDispatcher = Dispatchers.Default private set diff --git a/coroutinekit/src/test/kotlin/com/yangcyzhang/coroutinekit/ext/FlowExtTest.kt b/coroutinekit/src/test/kotlin/com/yangcyzhang/coroutinekit/ext/FlowExtTest.kt index 9f95b92..d1e67ae 100644 --- a/coroutinekit/src/test/kotlin/com/yangcyzhang/coroutinekit/ext/FlowExtTest.kt +++ b/coroutinekit/src/test/kotlin/com/yangcyzhang/coroutinekit/ext/FlowExtTest.kt @@ -1,6 +1,8 @@ package com.yangcyzhang.coroutinekit.ext +import kotlinx.coroutines.CancellationException import kotlinx.coroutines.flow.flow +import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.toList import kotlinx.coroutines.test.runTest import org.junit.jupiter.api.Assertions.assertEquals @@ -113,6 +115,15 @@ class FlowExtTest { assertEquals(listOf(1, 2, 3), results) } + @Test + fun `onEachCatching propagates CancellationException`() = runTest { + assertFailsWith { + flowOf(1) + .onEachCatching { throw CancellationException("cancel") } + .toList() + } + } + // ───────────────────────── mapNotNullCatching ───────────────────────── @Test @@ -134,4 +145,22 @@ class FlowExtTest { assertEquals(listOf("one"), results) } + + @Test + fun `mapNotNullCatching propagates CancellationException`() = runTest { + assertFailsWith { + flowOf(1) + .mapNotNullCatching { throw CancellationException("cancel") } + .toList() + } + } + + @Test + fun `flatMapLatestCatching propagates CancellationException`() = runTest { + assertFailsWith { + flowOf(1) + .flatMapLatestCatching { throw CancellationException("cancel") } + .toList() + } + } } diff --git a/coroutinekit/src/test/kotlin/com/yangcyzhang/coroutinekit/ext/SuspendExtTest.kt b/coroutinekit/src/test/kotlin/com/yangcyzhang/coroutinekit/ext/SuspendExtTest.kt index 3977b89..a341e04 100644 --- a/coroutinekit/src/test/kotlin/com/yangcyzhang/coroutinekit/ext/SuspendExtTest.kt +++ b/coroutinekit/src/test/kotlin/com/yangcyzhang/coroutinekit/ext/SuspendExtTest.kt @@ -3,6 +3,8 @@ package com.yangcyzhang.coroutinekit.ext import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.cancel +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.launch import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.jupiter.api.Assertions.assertEquals @@ -58,6 +60,23 @@ class SuspendExtTest { assertEquals("fallback", result) } + @Test + fun `withTimeoutOrDefault propagates parent cancellation`() = runTest { + var returnedFallback = false + val job = launch { + withTimeoutOrDefault(timeMillis = 10_000, defaultValue = Unit) { + kotlinx.coroutines.awaitCancellation() + } + returnedFallback = true + } + + testScheduler.runCurrent() + job.cancelAndJoin() + + assertTrue(job.isCancelled) + assertTrue(!returnedFallback) + } + // ───────────────────────── retry ───────────────────────── @Test From 975e8ba26a9a244dc639928a6141d22241121262 Mon Sep 17 00:00:00 2001 From: yangcyzhang Date: Mon, 12 Oct 2026 21:47:43 +0800 Subject: [PATCH 2/4] Enhance ManagedScope with custom onError exception handler and tests --- .../coroutinekit/lifecycle/ManagedScope.kt | 17 +++++++++++------ .../lifecycle/ManagedScopeTest.kt | 19 +++++++++++++++++++ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/lifecycle/ManagedScope.kt b/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/lifecycle/ManagedScope.kt index 53bfa7f..25e5eff 100644 --- a/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/lifecycle/ManagedScope.kt +++ b/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/lifecycle/ManagedScope.kt @@ -44,15 +44,18 @@ import kotlin.coroutines.CoroutineContext * @since 0.1.0 */ class ManagedScope( - dispatcher: CoroutineDispatcher = Dispatchers.Default + dispatcher: CoroutineDispatcher = Dispatchers.Default, + onError: ((Throwable) -> Unit)? = null ) : CoroutineScope, Closeable { private val supervisorJob = SupervisorJob() private val exceptionHandler = CoroutineExceptionHandler { _, throwable -> - // Log or handle uncaught exceptions from child coroutines. - // By default, we print to stderr. Override by passing a custom handler. - System.err.println("[CoroutineKit/ManagedScope] Uncaught exception: $throwable") + if (onError != null) { + onError(throwable) + } else { + System.err.println("[CoroutineKit/ManagedScope] Uncaught exception: $throwable") + } } override val coroutineContext: CoroutineContext = @@ -107,5 +110,7 @@ class ManagedScope( * @author yangcyzhang * @since 0.1.0 */ -fun managedScope(dispatcher: CoroutineDispatcher = Dispatchers.Default): ManagedScope = - ManagedScope(dispatcher) +fun managedScope( + dispatcher: CoroutineDispatcher = Dispatchers.Default, + onError: ((Throwable) -> Unit)? = null +): ManagedScope = ManagedScope(dispatcher, onError) diff --git a/coroutinekit/src/test/kotlin/com/yangcyzhang/coroutinekit/lifecycle/ManagedScopeTest.kt b/coroutinekit/src/test/kotlin/com/yangcyzhang/coroutinekit/lifecycle/ManagedScopeTest.kt index 627b5a4..1962dcb 100644 --- a/coroutinekit/src/test/kotlin/com/yangcyzhang/coroutinekit/lifecycle/ManagedScopeTest.kt +++ b/coroutinekit/src/test/kotlin/com/yangcyzhang/coroutinekit/lifecycle/ManagedScopeTest.kt @@ -89,4 +89,23 @@ class ManagedScopeTest { assertTrue(sibling2Completed, "Sibling 2 should have completed despite other child failing") scope.close() } + + @Test + fun `custom onError handler catches uncaught exceptions`() = runTest { + val capturedExceptions = mutableListOf() + val scope = ManagedScope( + dispatcher = StandardTestDispatcher(testScheduler), + onError = { capturedExceptions.add(it) } + ) + + scope.launch { + throw IllegalArgumentException("custom handler test") + } + + testScheduler.advanceUntilIdle() + + assertEquals(1, capturedExceptions.size) + assertTrue(capturedExceptions[0] is IllegalArgumentException) + scope.close() + } } From 90c9aeb2d51eb88d5cada1c87961580c6a148345 Mon Sep 17 00:00:00 2001 From: yangcyzhang Date: Mon, 12 Oct 2026 21:58:04 +0800 Subject: [PATCH 3/4] Ignore .artifacts directory in git --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 2ed4899..fccdfa0 100644 --- a/.gitignore +++ b/.gitignore @@ -41,3 +41,4 @@ jacoco/ *.swp *.swo *~ +/.artifacts/ From 40c635365509bad6a50f9be3a0c03c02772a07f2 Mon Sep 17 00:00:00 2001 From: yangcyzhang Date: Thu, 29 Oct 2026 16:47:12 +0800 Subject: [PATCH 4/4] Ensure CancellationException propagation in Flow operators and fix flatMapLatestCatching --- .../com/yangcyzhang/coroutinekit/ext/FlowExt.kt | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/ext/FlowExt.kt b/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/ext/FlowExt.kt index b7af4b9..e3e968b 100644 --- a/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/ext/FlowExt.kt +++ b/coroutinekit/src/main/kotlin/com/yangcyzhang/coroutinekit/ext/FlowExt.kt @@ -145,13 +145,15 @@ fun Flow.onEachCatching(action: suspend (T) -> Unit): Flow = @Suppress("OPT_IN_USAGE") fun Flow.flatMapLatestCatching( transform: suspend (T) -> Flow -): Flow = flatMapLatest { value -> - try { - transform(value) - } catch (e: CancellationException) { - throw e - } catch (e: Exception) { - flow { /* emit nothing on error */ } +): Flow = flow { + collect { value -> + try { + transform(value).collect { emit(it) } + } catch (e: CancellationException) { + throw e + } catch (_: Exception) { + // suppress other exceptions and continue + } } }