https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

ansman

01/27/2023, 3:33 PM
Is it really correct that this code:
Copy code
withContext(Dispatchers.Unconfined) {
   println(1)
   withContext(Dispatchers.Unconfined) { // Nested unconfined
       println(2)
   }
   println(3)
}
can really print
1, 3, 2
? If the inner
withContext
was a
launch
I'm fully on board with the fact that the order is undefined. But since
withContext
actually returns something it would mean that this code:
Copy code
withContext(Dispatchers.Unconfined) {
   val result = withContext(Dispatchers.Unconfined) { 1 + 1 }
   println(result)
}
Could be broken?
s

Sam

01/27/2023, 3:37 PM
What makes you say that it could print
1, 3, 2
? Have you seen that claim made somewhere? Since there are no calls to
launch
or
async
, I think your reasoning is correct and this code should execute sequentially.
a

ansman

01/27/2023, 3:37 PM
From the kdoc for `Dispatchers.Unconfined`:
Copy code
For example, the following code:
withContext(Dispatchers.Unconfined) {
   println(1)
   withContext(Dispatchers.Unconfined) { // Nested unconfined
       println(2)
   }
   println(3)
}
println("Done")

Can print both "1 2 3" and "1 3 2", this is an implementation detail that can be changed. But it is guaranteed that "Done" will be printed only when both withContext are completed.
s

Sam

01/27/2023, 3:40 PM
Huh. I agree with you, that documentation does not match my understanding of how
withContext
works.
a

ansman

01/27/2023, 3:41 PM
I'm feeling fairly sure that they meant to use
launch
in their example
a

ansman

02/01/2023, 2:40 PM
My PR that fixes this just landed
s

Sam

02/01/2023, 2:44 PM
😬 just a bit later on it still refers to “both
withContext
calls” though.
I’m not sure what the wording for that should be after the change.
a

ansman

02/01/2023, 2:46 PM
Damn, I missed that. Will fix
4 Views