What could be the best approch to call a suspensio...
# coroutines
a
What could be the best approch to call a suspension function inside a coroutine exception handler?
Copy code
val handler = CoroutineExceptionHandler { context, exception ->
	Log.d("exception", exception.message ?: "", exception)
	suspensionFunc() // <--- This part, such as for calling a network requests.
}
What i thought of are: 1. Wrap the context with a
CoroutineScope()
and then launch with it. 2. Call using
runBlocking{}
, but isn't best idea cause it could affect app performance specially if ran on Main threads 3. Use
GlobalScope()
4. Use
GlobalScope()
but launch to IO dispatcher.
e
Do you care about catching the exception in the event your network request fails?
a
For exception logging, if network request fails then i'd need to add extra checks.
e
I might create a separate coroutine scope with a supervisor job specifically for these network requests then, then add a CEH on that scope so you can log errors if they occur. Maybe just have it backed by a dispatcher with 1-2 threads depending on how often you expect the exception handler to catch errors. Whenever you need to invoke these suspending functions you can then launch the suspending functions inside the scope.
a
What's the purpose of supervisor job here? And how would you provide scope to the CEH?
e
Supervisor job: if an exception is thrown in a scope with an normal job, the job at the top level of the scope will be cancelled on uncaught exceptions so you can’t launch anything else in it Providing scope: You can define a coroutinescope as a variable from a threadpool via
asCoroutineDispatcher()
. Just define it around the same place you define the CEH and then inside the CEH you should be able to do:
Copy code
val handler = CoroutineExceptionHandler { context, exception ->
    // do your logging...
    coroutineScopeYouDefined.launch { suspensionFunc() }
}
a
@Evan R. I don't like to create a dedicated scope for this purpose at least in android applications, etc.
e
Ok, then you need to choose a scope and just launch it there. GlobalScope might be the way to go in that case
Just make sure to handle exceptions in your launch
a
okey thanks!