Could someone explained what the Key in the CoroutineContextHandler is used for? I can’t figure it out from the documentation
m
mbonnin
12/21/2021, 1:02 PM
It's mostly an implementation détail to retrieve the CoroutineExceptionHandler in a CoroutineContext. See https://link.medium.com/sJGX3mKwamb for more details
s
streetsofboston
12/21/2021, 3:30 PM
See the CoroutineContext as a (typed) map. You can put and get an Element by providing it a Key. Putting another Element with the same key will replace the current Element, if there is one.
By convention (not enforced by the language or the compiler), a subtype of an Element should have companion object that is a subtype of Key.
Copy code
class MyElement(...) : Element {
...
fun hello() { ... }
companion object : Key<MyElement>
}
...
...
coroutineContext[MyElement] = MyElement(...)
...
coroutineContext[MyElement].hello()
^-- key is companion object