then/catch/finally
semantics for coroutines may feel like a step backward towards promises
, however a few use cases are:
Reduce try {} catch {}
boilerplate
val job : Deferred<T> = async { ... }
job.finally { it: Result<T> ->
when (it) {
is Result.Value -> println(it.value)
is Result.Error -> println(it.error)
}
}
Error Recovery
runBlocking {
val job = async(coroutineContext) {
delay(200)
throw Exception("Oops")
}
val result = job.catch(coroutineContext) { it: Throwable ->
println("catch: ${it.message}") //=> catch: Oops
"World"
}.await()
println("result: Hello $result") //=>result: Hello World
}
Gimme the Result
val job : Deferred<T> = async { ... }
job.then {
println(it)
}
A Deferred for a Deferred makes the world…
val job : Deferred<Int> = async { 1 }
val result = job.then { it + 1 }.await()
println(result) //=> 2
Feedback welcome.