nowinandroid
nowinandroid copied to clipboard
Calling ensureActive instead of re-throwing CancellationException in suspendRunCatching
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?