Skip to content
Closed
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,4 @@ jacoco/
*.swp
*.swo
*~
/.artifacts/
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ val future: CompletableFuture<User> = suspendToFuture {
### 8. Java Interop — Callback → Flow

```kotlin
val sensorFlow: Flow<SensorData> = callbackFlow(
val sensorFlow: Flow<SensorData> = callbackToFlow(
register = { onResult, onError ->
sensorManager.register(object : SensorListener {
override fun onData(d: SensorData) = onResult(d)
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -102,7 +102,8 @@ fun <T> Flow<T>.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:
Expand All @@ -121,15 +122,20 @@ fun <T> Flow<T>.retryWithDelay(
*/
fun <T> Flow<T>.onEachCatching(action: suspend (T) -> Unit): Flow<T> =
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
Expand All @@ -139,18 +145,22 @@ fun <T> Flow<T>.onEachCatching(action: suspend (T) -> Unit): Flow<T> =
@Suppress("OPT_IN_USAGE")
fun <T, R> Flow<T>.flatMapLatestCatching(
transform: suspend (T) -> Flow<R>
): Flow<R> = flatMapLatest { value ->
try {
transform(value)
} catch (e: Exception) {
flow { /* emit nothing on error */ }
): Flow<R> = flow {
collect { value ->
try {
transform(value).collect { emit(it) }
} catch (e: CancellationException) {
throw e
} catch (_: Exception) {
// suppress other exceptions and continue
}
}
}

/**
* 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
Expand All @@ -162,6 +172,8 @@ fun <T, R : Any> Flow<T>.mapNotNullCatching(
): Flow<R> = transform { value ->
try {
transform(value)?.let { emit(it) }
} catch (e: CancellationException) {
throw e
} catch (_: Exception) {
// Skip items that fail transformation
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -49,6 +50,7 @@ suspend fun <T> suspendRunCatching(block: suspend () -> T): Result<T> = 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.
Expand All @@ -73,11 +75,7 @@ suspend fun <T> 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
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down Expand Up @@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -113,6 +115,15 @@ class FlowExtTest {
assertEquals(listOf(1, 2, 3), results)
}

@Test
fun `onEachCatching propagates CancellationException`() = runTest {
assertFailsWith<CancellationException> {
flowOf(1)
.onEachCatching { throw CancellationException("cancel") }
.toList()
}
}

// ───────────────────────── mapNotNullCatching ─────────────────────────

@Test
Expand All @@ -134,4 +145,22 @@ class FlowExtTest {

assertEquals(listOf("one"), results)
}

@Test
fun `mapNotNullCatching propagates CancellationException`() = runTest {
assertFailsWith<CancellationException> {
flowOf(1)
.mapNotNullCatching<Int, String> { throw CancellationException("cancel") }
.toList()
}
}

@Test
fun `flatMapLatestCatching propagates CancellationException`() = runTest {
assertFailsWith<CancellationException> {
flowOf(1)
.flatMapLatestCatching<Int, Int> { throw CancellationException("cancel") }
.toList()
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Throwable>()
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()
}
}
Loading