Astronaut4449
12/31/2021, 4:30 PMsuspend fun CoroutineScope.dontDoThis() {
// Warning: Ambiguous coroutineContext due to
// CoroutineScope receiver of suspend function
launch { }
}
I noticed that some Ktor classes extend CoroutineScope
and act as receiver of suspend functions at the same time. E.g.:
fun Routing.websocket() {
webSocket { // this: DefaultWebSocketServerSession
// No warning although DefaultWebSocketServerSession
// extends CoroutineScope and is used as receiver of
// a suspend function
launch { }
}
}
This can lead to problems where the coroutine scope is shadowed:
fun Routing.scopeProblem() {
webSocket { // this: DefaultWebSocketServerSession
withContext(SomeContextElement()) {
someWebSocketLogic()
}
}
}
suspend fun DefaultWebSocketServerSession.someWebSocketLogic() {
// Shadowed coroutines scope
coroutineContext[SomeContextElement] // null (refers to receiver, skipping withContext of upper function)
currentCoroutineContext()[SomeContextElement] // SomeContextElement@xyz (refers to suspend function)
}
What are your thoughts on this?