nowinandroid icon indicating copy to clipboard operation
nowinandroid copied to clipboard

Calling ensureActive instead of re-throwing CancellationException in suspendRunCatching

Open azabost opened this issue 6 months ago • 5 comments

In suspendRunCatching, a CancellationException gets re-thrown:

https://github.com/android/nowinandroid/blob/689ef92e41427ab70f82e2c9fe59755441deae92/core/data/src/main/kotlin/com/google/samples/apps/nowinandroid/core/data/SyncUtilities.kt#L58

However, according to this post (further acknowledged here), it's more advisable to ensureActive() instead. Maybe like this?

private suspend fun <T> suspendRunCatching(block: suspend () -> T): Result<T> = try {
    Result.success(block())
} catch (cancellationException: CancellationException) {
    currentCoroutineContext().ensureActive() // if _our_ coroutine was cancelled - respect the cancellation
    Result.failure(cancellationException) // otherwise, just treat it as a failure
} catch (exception: Exception) {
    Log.i(
        "suspendRunCatching",
        "Failed to evaluate a suspendRunCatchingBlock. Returning failure Result",
        exception,
    )
    Result.failure(exception)
}

What do you think?

azabost avatar May 20 '25 00:05 azabost