You can also remove context elements from a combined context if needed. To do this, you need to have a reference to the key of the element that you want to remove. For example, let's modify the previous example so that we separate the combined context:
fun main(args: Array<String>) = runBlocking {
val dispatcher = newSingleThreadContext("myDispatcher")
val handler = CoroutineExceptionHandler({ _, throwable ->
println("Error captured")
println("Message: ${throwable.message}")
})
// Combine two contexts together
val context = dispatcher + handler
// Remove one element from the context
val tmpCtx = context.minusKey(dispatcher.key)
launch(tmpCtx) {
println("Running in ${Thread.currentThread().name}")
TODO("Not implemented!")
}.join()
}
This will be the same as if we use launch(handler) {...}. Notice here that the thread corresponds to the default dispatcher instead of it being the thread of dispatcher: