Created
April 3, 2022 11:09
-
-
Save jacobras/9d70964ba944d4fee51fdae6e57f30a6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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