For example, let's say that you want to have a coroutine running in a specific thread, and at the same time you want to set an exception handler for it. To do this, you can combine both by using the plus operator:
main(args: Array<String>) = runBlocking {
val dispatcher = newSingleThreadContext("myDispatcher")
val handler = CoroutineExceptionHandler({ _, throwable ->
println("Error captured")
println("Message: ${throwable.message}")
})
launch(dispatcher + handler) {
println("Running in ${Thread.currentThread().name}")
TODO("Not implemented!")
}.join()
}
In this case, we are combining a single thread dispatcher with an exception handler, and the coroutine will behave accordingly:
You can, of course, create a variable to hold the combined contexts, to avoid having to use the plus more than once:
val context = dispatcher + handler
launch(context) { ... }