android / android/nowinandroid

Calling ensureActive instead of re-throwing CancellationException in suspendRunCatching

Open
#1,876 5 comments 1 reaction 0 assignees View on GitHub
Dominant language
Kotlin
Stars
21.8k
Forks
4.6k
Avg merge
19h 20m
Merged PRs (30d)
2

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](https://betterprogramming.pub/the-silent-killer-thats-crashing-your-coroutines-9171d1e8f79b) (further acknowledged [here](https://github.com/Kotlin/kotlinx.coroutines/issues/3658#issuecomment-1465747377)), it's more advisable to `ensureActive()` instead. Maybe like this?

```kotlin
private suspend fun suspendRunCatching(block: suspend () -> T): Result = 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?

Contributor guide

Open the contributing guide

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.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.