More about contexts
As we have seen, the context can define many different details of how a coroutine will behave. Contexts can also be operated on to define mixed behaviors. Let's talk about how contexts can be used in more creative ways.
Mixing contexts
As we have seen in this chapter, there are different types of elements that can be part of a context. We can mix these elements to create a context that meets our needs.
Combining contexts
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...