PHondogo
10/04/2023, 7:46 AMSam
10/04/2023, 7:46 AMval dispatcher = coroutineContext[CoroutineDispatcher]
PHondogo
10/04/2023, 9:06 AMokarm
10/04/2023, 10:17 AMcurrentCoroutineContext()[CoroutineDispatcher]
instead.
https://pl.kotl.in/9oDQ8N8M7Peter Farlow
10/04/2023, 3:46 PMSam
10/04/2023, 4:02 PMcoroutineContext
. 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.rocketraman
10/04/2023, 5:51 PM