Hello! How to get current coroutine dispatcher?
# coroutines
p
Hello! How to get current coroutine dispatcher?
s
val dispatcher = coroutineContext[CoroutineDispatcher]
p
Thanks!
🍻 1
o
You may need to access it via
currentCoroutineContext()[CoroutineDispatcher]
instead. https://pl.kotl.in/9oDQ8N8M7
👍 1
p
interesting that the property vs function have different answers
s
The reason is that there are actually two properties named
coroutineContext
. One of them is a top-level property that gets the current coroutine context in any
suspend
function. The other is a member property of
CoroutineScope
, and gets you the context from that scope. When you're inside a
suspend
function and have a
CoroutineScope
available as a receiver at the same time, the coroutine scope member property shadows the top-level property, and so you always get the coroutine context from the scope instead of from the current function. In many cases that's not an issue—for example inside coroutine builder functions like
launch
, where the scope's context is the same as the context of the current coroutine. But every so often you encounter a scenario where that's not the case. Flows are a common culprit, because a flow can easily be declared in one place and executed in another. The
currentCoroutineContext()
function was introduced as a way to disambiguate between the two implementations of
coroutineContext
. It has no receiver so it will always point to the context of the current function, ignoring any
CoroutineScope
instance that might be hanging around.
👍 2
r
> When you're inside a suspend function and have a CoroutineScope available as a receiver at the same time This might be true if the receiver is in scope in the current suspend function. But its worth noting that explicitly declaring a suspend function with a CoroutineScope receiver is considered bad practice because the function's behavior is unclear to the caller. See https://elizarov.medium.com/explicit-concurrency-67a8e8fd9b25.
408 Views