1

Let's say I have the following coroutine:

lifecycleScope.launch(Dispatchers.IO) {

}

If I want to switch Dispatchers within the above coroutine, I can do it in the following two ways: withContext(Dispatchers.Main) {} or launch(Dispatchers.Main) {}.

What's the difference between the two ways of switching Dispatchers? Are they basically doing the same thing, but with a different syntax?

Tom Darious
  • 434
  • 6
  • 18
  • 1
    Does this answer your question? [When to use withContext?](https://stackoverflow.com/questions/64060268/when-to-use-withcontext) – Mark Aug 13 '22 at 19:18
  • @Mark No because it doesn't explain the difference between switching contexts using `launch` vs `withContext` within a coroutine? – Tom Darious Aug 13 '22 at 19:22
  • 2
    Setting a dispatcher in `launch` changes the dispatcher used in the primary coroutine when you launch it. Using `withContext` lets you switch dispatchers for a section of code in the middle of a coroutine. You seem to already know this, so it's not clear what you are asking here... Note that `withContext` will suspend while `launch` will not. – Tyler V Aug 13 '22 at 19:26
  • 2
    `launch` runs the block in a new coroutine, `withContext` is run in the current coroutine this is the main difference when used within a `CoroutineScope`. – Mark Aug 13 '22 at 19:26
  • @TylerV @Mark These were the answers that I was looking for originally. I know you can use both to change dispatchers within the parent coroutine, I just didn't understand the difference between the two and when you would use one over the other. To sum up, `withContext` will suspend and continue in the current coroutine, but with a different dispatcher and `launch` won't suspend and launch a new coroutine instead of staying in the parent coroutine. – Tom Darious Aug 13 '22 at 20:05

0 Answers0