Skip to content

Instantly share code, notes, and snippets.

@jacobras
Created April 3, 2022 11:09
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jacobras/9d70964ba944d4fee51fdae6e57f30a6 to your computer and use it in GitHub Desktop.
import kotlinx.coroutines.CancellationException
/**
* Like [runCatching], but with proper coroutines cancellation handling. Also only catches [Exception] instead of [Throwable].
*
* Cancellation exceptions need to be rethrown. See https://github.com/Kotlin/kotlinx.coroutines/issues/1814.
*/
inline fun <R> resultOf(block: () -> R): Result<R> {
return try {
Result.success(block())
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Result.failure(e)
}
}
/**
* Like [runCatching], but with proper coroutines cancellation handling. Also only catches [Exception] instead of [Throwable].
*
* Cancellation exceptions need to be rethrown. See https://github.com/Kotlin/kotlinx.coroutines/issues/1814.
*/
inline fun <T, R> T.resultOf(block: T.() -> R): Result<R> {
return try {
Result.success(block())
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Result.failure(e)
}
}
/**
* Like [mapCatching], but uses [resultOf] instead of [runCatching].
*/
inline fun <R, T> Result<T>.mapResult(transform: (value: T) -> R): Result<R> {
val successResult = getOrNull()
return when {
successResult != null -> resultOf { transform(successResult) }
else -> Result.failure(exceptionOrNull() ?: error("Unreachable state"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment