Marcelo Hernandez
07/08/2019, 5:16 PMSingles
, Maybes
, and Completables
to suspend
functions. I feel that with Rx, error handling is pretty much try/catch(Throwable)
behind the scenes. So when switching over to coroutines, one might "naively" start using runCatching { ... }.onSuccess { ... }.onFailure { ... }
or basic try/catch(Throwable)
. The issue with this is that a CancellationException
will also be caught when attempting to cancel a coroutine. Does this mean that before refactoring to suspend
functions, one should begin defining custom, domain-specific Exceptions or leverage some sort of Result
type in order to avoid try/catch(Throwable)
?louiscad
07/08/2019, 6:33 PMcatch(ignored: CancellationException)
first, or from which you rethrow (important if there's only custom suspending functions that don't check for cancellation). Another is to catch only the expected exceptions (might be risky if you don't know what can be thrown). You can also check e is CancellationException
and rethrow it.Marcelo Hernandez
07/08/2019, 6:46 PMMarcelo Hernandez
07/08/2019, 6:49 PMdoRxAsyncWork()
.subscribeOn(...)
.observeOn(...)
.subscribe(
{ ... },
{ error -> // perform error handling }
)
to
try {
doSuspendingWork()
} catch (ex: CancellationException) {
throw ex
} catch (ex: Throwable) {
// perform error handling
}
Marcelo Hernandez
07/08/2019, 7:00 PMMarcelo Hernandez
07/08/2019, 7:00 PMrunCatching
utility that catches and re-throws the CancellationException
.streetsofboston
07/08/2019, 7:30 PMException
, or Throwable
, etc. In this case it is somewhat forced on you to catch specific ones onlyMarcelo Hernandez
07/08/2019, 7:37 PMObservable
Rx code to suspend
functions with minimal effort.Paul Woitaschek
07/08/2019, 8:08 PMMarcelo Hernandez
07/14/2019, 8:16 PMFlows
will be getting a catch
operator that properly handles CancellationExceptions
.
âExceptions in Kotlin Flowsâ by Roman Elizarov https://link.medium.com/AenSuqlckYMarcelo Hernandez
07/14/2019, 8:17 PMrunCatching
variant for non-Flow
suspend
code that also takes CancellationExceptions
into account?Stephane Maldini
07/15/2019, 10:07 PMStephane Maldini
07/15/2019, 10:08 PM