Sobes.tech
Junior — Middle

What methods can be used to switch the execution of coroutines within a single thread?

sobes.tech AI

Answer from AI

In Kotlin, coroutines can be switched within the same thread using various dispatchers and functions:

  • withContext(Dispatchers.Main) — switch to the main (UI) thread.
  • withContext(Dispatchers.Default) — switch to a thread pool for CPU-intensive tasks.
  • withContext(Dispatchers.IO) — switch to a thread pool for input/output operations.

Additionally, you can use yield() to voluntarily transfer control to another coroutine within the current thread.

Example of context switching:

launch {
    // Work on the main thread
    withContext(Dispatchers.IO) {
        // Perform input/output operation
    }
    // Return to the main thread
}
What methods can be used to switch the execution of… - sobes.tech