Junior — Middle
Kuidas saab ühe niidi raames korutinate täitmist vahetada?
sobes.tech AI
Vastus AI-lt
In Kotlin, coroutines can be switched within the same thread using different 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, yield() can be used 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
}