Hey guys. I have a problem with Dispatchers.Main.i...
# coroutines
m
Hey guys. I have a problem with Dispatchers.Main.immediete. I know the theory, that it guarantees to not redispatch when using withContext from immediete to immediete, but in my experiments, I observe the same behavior when I just use Dispatchers.Main. Do you know any specific code that could show a difference between Dispatchers.Main and Dispatchers.Main.immediete?

https://www.youtube.com/watch?v=QIYgn7KlUfo▾

It might be a result of using setMain. I will try to show a difference in Android app.
s
If I understand correctly, the use case for Main.immediate is really when you're already running on the main thread but not yet running in a coroutine—for example in the
onCreate()
method of an Android activity. e.g.
Copy code
override fun onCreate(savedInstanceState: Bundle?) {
  super.onCreate(savedInstanceState)
  scope.launch(Dispatchers.Main) { 
    // queued for dispatch; runs second
    println("Second")
  }
  
  scope.launch(Dispatchers.Main.immediate) { 
    // runs first (inline), no dispatch 
    // (because onCreate was already running on the main thread)
    println("First")
  }
}
Android's not my area of expertise though, so maybe I misunderstood what you're asking about or I got some details wrong. Does this help demonstrate the difference you were looking for?
I think that
withContext
always makes the same guarantee about not redispatching when the dispatcher hasn't changed, regardless of which dispatcher you're using, though I can't find that exact wording in the documentation right now 🤔
c
I don't know about the documentation, but the code does avoid redispatching if the dispatcher hasn't changed
m
Thanks