Uchun Lee
09/01/2019, 11:07 PMlaunchCatching(
block = {
getRandomNumber()
},
result = {
println("result is $it")
}
).invokeOnCompletion {
it is Throwable
}
fun <T> CoroutineScope.launchCatching(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T,
result: (result: Result<T>) -> Unit
) = launch(context, start) {
result(
runCatching {
block()
}
)
}
fun <T> CoroutineScope.launchCatching(
context: CoroutineContext = EmptyCoroutineContext,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T,
onSuccess: (value: T) -> Unit,
onFailure: (exception: Throwable) -> Unit
) = launch(context, start) {
runCatching {
block()
}.fold(
onSuccess,
onFailure
)
}
Dominaezzz
09/02/2019, 2:41 PMlaunch
why not just have a suspend function. This seems a bit round about.Uchun Lee
09/02/2019, 11:32 PMlaunch
is just finished meet a exception.
If I want to know what exception is. I can know using by invokeOnCompletion
. (If I adding CoroutineExceptionHandler)
But It is separated successful and failure block. successful is run on coroutine and failure is others.
So I tried encapsulate suspend function by Result class. But I don’t want modify compile option because of this document (https://github.com/Kotlin/KEEP/blob/success-or-failure/proposals/stdlib/success-or-failure.md)
And Next I’m wrapped runCatching
or try / catch
each suspend function. But It is simplicity repetition. So I tried it.Evan R.
09/03/2019, 12:50 PMResult<T>
. As an example:
sealed class Result<T>
class SuccessResult<T>(val result: T): Result<T>
class FailureResult<T>(val error: Throwable): Result<T>
suspend fun doesNotThrowAnyErrors(): Result<String> {
return try {
SuccessResult(mayThrowSomeError())
} catch (e: Exception) {
FailureResult(e)
}
}
// Usage
suspend fun usageExample() {
when (val computationResult = doesNotThrowAnyErrors()) {
is SuccessResult -> println(computationResult.value)
is FailureResult -> println("Got an error!")
}
}
async {}
rather than launch {}
as the former actually returns a computation result. Only use launch {}
if you don’t care about the result of the launched coroutine.Uchun Lee
09/04/2019, 9:01 PM