fix: ignore CancellationException in suspend functions (#1794)

* fix: ignore `CancellationException` in suspend functions

Signed-off-by: Aditya Wasan <adityawasan55@gmail.com>

* build(coroutine-utils): use `api` instead of `implementation`

Co-authored-by: Harsh Shandilya <me@msfjarvis.dev>

Co-authored-by: Harsh Shandilya <me@msfjarvis.dev>
This commit is contained in:
Aditya Wasan 2022-03-23 18:18:06 +05:30 committed by GitHub
parent cf3ae17b84
commit 9c9616d047
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 57 additions and 7 deletions

View file

@ -10,4 +10,5 @@ plugins {
dependencies {
implementation(libs.kotlin.coroutines.core)
implementation(libs.dagger.hilt.core)
api(libs.thirdparty.kotlinResult)
}

View file

@ -0,0 +1,48 @@
@file:OptIn(ExperimentalContracts::class)
@file:Suppress("RedundantSuspendModifier")
package dev.msfjarvis.aps.util.coroutines
import com.github.michaelbull.result.Err
import com.github.michaelbull.result.Ok
import com.github.michaelbull.result.Result
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
import kotlinx.coroutines.CancellationException
/**
* Calls the specified function [block] with [this] value as its receiver and returns its
* encapsulated result if invocation was successful, catching any [Throwable] except
* [CancellationException] that was thrown from the [block] function execution and encapsulating it
* as a failure.
*/
public suspend inline fun <V> runSuspendCatching(block: () -> V): Result<V, Throwable> {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
Ok(block())
} catch (e: Throwable) {
if (e is CancellationException) throw e
Err(e)
}
}
/**
* Calls the specified function [block] with [this] value as its receiver and returns its
* encapsulated result if invocation was successful, catching any [Throwable] except
* [CancellationException] that was thrown from the [block] function execution and encapsulating it
* as a failure.
*/
public suspend inline infix fun <T, V> T.runSuspendCatching(
block: T.() -> V
): Result<V, Throwable> {
contract { callsInPlace(block, InvocationKind.EXACTLY_ONCE) }
return try {
Ok(block())
} catch (e: Throwable) {
if (e is CancellationException) throw e
Err(e)
}
}