Calling ensureActive instead of re-throwing CancellationException in suspendRunCatching

Open
#1,876 5 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
45/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Stale
Tech stack
kotlin
Domain
mobile

Research direction

Start in core/data/src/main/kotlin/com/google/samples/apps/nowinandroid/core/data/SyncUtilities.kt at suspendRunCatching around line 58. Check the coroutine cancellation behavior described in the issue and verify that the completed behavior distinguishes cancellation of the current coroutine from a cancellation reported as a failure.

Written by the indexing model from the issue text.

Description

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?

Dominant language
Kotlin
Stars
22.1k
Forks
4.7k
PR merge metrics
No merged PRs in 30d

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from android/nowinandroid

All issues in android/nowinandroid

Similar issues

More Kotlin issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.