lukaswelte
10/12/2018, 1:13 PMCoroutineScope
which is onError
? So in case any of the coroutines in the scope are cancelled or failing it will not cancel the parent scope routines, but instead invoke the error handler. Or is try-catch
around the coroutineScope {}
currently the only way?elizarov
10/12/2018, 1:14 PMCoroutineExceptionHandler
that does it. It is explained here: http://kotlinlang.org/docs/reference/coroutines/exception-handling.htmllukaswelte
10/12/2018, 1:16 PMdekans
10/12/2018, 1:20 PMasync
provides a Deferred
, which can tell you if an exception occuredlukaswelte
10/12/2018, 1:22 PMstartFetching
in this example is not cancelling the parent scope and would like to not have try-catch
around the startFetching
call, but rather something like
val x = startFetching().ifError { emptyList() }
dekans
10/12/2018, 1:25 PMCoroutineExceptionHandler
seems a good tool for you thenelizarov
10/12/2018, 1:25 PMifError
function as an extension.fun <T> Deferred<T>.ifError(defaultValue: () -> T): Deferred<T> = GlobalScope.async {
try { await() } catch(e: Throwable) { defaultValue() }
}
Deferred
is generally a bad idea from the design standpoint. You should design your API using suspending functions, so that you fetching function looks like suspend fun fetch(): T
, for examplelukaswelte
10/12/2018, 1:30 PMDeferred<T>
but T
as response)elizarov
10/12/2018, 1:30 PMrunCatching { startFetching() }.getOrElse { emptyList() }
startFetching
code, you’ll never know about that.lukaswelte
10/12/2018, 3:13 PMrunCatching
is nice. Thank you for your thoughts.
I’ll create my own little function which will catch the exception, report/log it and then return the fallback.kingsley
10/12/2018, 8:58 PMsupervisorScope
or SupervisorJob
might also be something to consider for this use case