https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

Animesh Sahu

02/26/2020, 2:21 PM
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

Evan R.

02/26/2020, 2:31 PM
Do you care about catching the exception in the event your network request fails?
a

Animesh Sahu

02/26/2020, 2:33 PM
For exception logging, if network request fails then i'd need to add extra checks.
e

Evan R.

02/26/2020, 2:39 PM
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

Animesh Sahu

02/26/2020, 2:42 PM
What's the purpose of supervisor job here? And how would you provide scope to the CEH?
e

Evan R.

02/26/2020, 2:52 PM
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

Animesh Sahu

02/26/2020, 3:01 PM
@Evan R. I don't like to create a dedicated scope for this purpose at least in android applications, etc.
e

Evan R.

02/26/2020, 3:01 PM
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

Animesh Sahu

02/26/2020, 3:02 PM
okey thanks!
3 Views