CodeGym /Courses /Kotlin SELF /withContext and dispatcher in a coroutine: switching the ...

withContext and dispatcher in a coroutine: switching the execution location

Kotlin SELF
Level 53, Lesson 1
Available

1. Why switch the execution location

When you’re just starting with coroutines, it’s easy to fall into a trap: “If I have suspend, I can write anything, and it will automatically become fast.” Alas, no—coroutines do not cancel physics. There is code that loads the CPU (calculates, sorts, compresses), and there is code that waits for I/O (file, network, DB, external system). withContext is a way, inside one coroutine, to say: “do this small piece in another place,” without creating a separate task and without complicating the structure.

It’s important to understand the key idea: coroutines are about controlled boundaries and a clear structure, and withContext is about local, careful switching of execution conditions—most often, the dispatcher.

When people say “coroutine context,” it’s easy to imagine something philosophical, but in practice it’s quite a concrete thing: a set of settings that the coroutine carries with it. In kotlinx.coroutines, important elements of the context include, for example, Job (lifecycle) and CoroutineDispatcher (where we run)—this is part of the core coroutine model.

Today we are mostly interested in the dispatcher. In simplified (but useful) terms, you can think of it like this:

  • the dispatcher is responsible for which threads and which pool your code runs on;
  • Dispatchers.Default is usually suitable for CPU tasks (computations);
  • Dispatchers.IO is usually suitable for I/O tasks (waiting for input/output).

Let’s draw a small diagram so we don’t have to keep everything in our head as a “cloud”:

flowchart TD
    A[Coroutine] --> B[CoroutineContext]
    B --> C[Job: lifecycle]
    B --> D[Dispatcher: where we run]
    D --> E[Dispatchers.Default: CPU]
    D --> F[Dispatchers.IO: I/O]

And the key thought: withContext changes the execution context for a block of code (usually the dispatcher is what you change), rather than “launching another coroutine.”

2. What withContext does and why it is suspend

withContext looks like a regular function where we pass an “execution mode” (for example, Dispatchers.IO) and a code block. But internally it does an important thing: it suspends the current coroutine, switches its execution to another context, runs the block, and returns the result back.

In meaning, it’s very similar to the phrase: “Go to the other kitchen, quickly make tea, come back, and we’ll continue the conversation.” The coroutine remains the same, the execution story remains sequential, it’s just that a piece of work is done “somewhere else.”

Since withContext can suspend execution, it is a suspend function. That means you can call it only from a coroutine or from another suspend function. If you try to call it from a regular function, the compiler is right to forbid it.

A minimal “straightforward” example:

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext

fun main() = runBlocking {
    val x: Int = withContext(Dispatchers.Default) {
        1 + 2 + 3
    }
    println("x = $x") // x = 6
}

Notice a nice detail: withContext { ... } is an expression—it returns the value of the block. So we can write fairly “normal” code, without extra temporary variables and without async/await if we don’t need parallelism.

4. withContext is not about parallelism

A common beginner (and very human) mistake: see Dispatchers.IO and think “aha, these are threads, so it will run in parallel.” But withContext is not “in parallel,” it’s “in another place, but still sequential.”

To avoid confusion, let’s fix the comparison in a table:

Tool What it does Returns When to use
launch { ... }
creates a new coroutine for actions
Job
when you need to run an action in parallel and then (possibly) wait for it
async { ... }
creates a new coroutine for a result
Deferred<T>
when you need to compute a value in parallel and then call await()
withContext(ctx) { ... }
does not create a new coroutine, but runs a piece in another context the block result (T) when you need sequential logic, but a section must run on another dispatcher

If you want a very short rule: launch/async is “create a separate task,” withContext is “do it here, but in another place”.

5. Look at the thread name and see the switch

To actually believe what’s happening (instead of just “taking the docs on faith”), it’s useful to print the thread name. Yes, we promised “not to think about threads,” but sometimes looking once is useful—like in cooking: you see once that the oven is hot, and after that you stop checking with your hand every time.

Let’s make a small logger:

import kotlinx.coroutines.runBlocking

private fun log(msg: String) {
    println("$msg (thread=${Thread.currentThread().name})")
}

fun main() = runBlocking {
    log("start")
    log("still start")
}

The output will depend on the environment, but the format will look roughly like this:

start (thread=main)
still start (thread=main)

Now let’s add withContext and see whether the thread changes:

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext

private fun log(msg: String) {
    println("$msg (thread=${Thread.currentThread().name})")
}

fun main() = runBlocking {
    log("before")
    withContext(Dispatchers.Default) {
        log("inside Default")
    }
    log("after")
}

Possible output (approximate):

before (thread=main)
inside Default (thread=DefaultDispatcher-worker-1)
after (thread=main)

And here it’s important not to draw the wrong conclusion. This does not mean that “a new coroutine was created.” It means that execution of this piece of code was handed off to another dispatcher, and after the block we returned to the original context.

6. Mini-app: console cash register, CPU and I/O

So the examples are not a set of “spherical coroutines in a vacuum,” let’s continue a single storyline. Imagine we have a console “cash register” app: it produces a receipt for an order.

Inside there are two fundamentally different stages:

  • “get prices”—in reality this could be reading from a file/DB/network (i.e., I/O), but for now we’ll simulate it with Thread.sleep;
  • “calculate total and discount”—these are computations (CPU), so it makes sense to keep them in Dispatchers.Default.

First, let’s create a simple data model:

data class Order(
    val id: Int,
    val items: List<String>
)

data class Receipt(
    val orderId: Int,
    val total: Int
)

Now let’s implement “loading the price list.” We intentionally use Thread.sleep to emphasize: this is a blocking I/O simulation. In real code, there would be file/DB requests instead, but for now the idea of choosing the dispatcher is what matters.

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

suspend fun loadPriceList(): Map<String, Int> =
    withContext(Dispatchers.IO) {
        Thread.sleep(80) // I/O simulation
        mapOf("coffee" to 120, "tea" to 80, "cake" to 150)
    }

Now let’s compute the total. Here we “deliberately” use Default as the place for computations:

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

suspend fun calculateTotal(order: Order, prices: Map<String, Int>): Int =
    withContext(Dispatchers.Default) {
        order.items.sumOf { item -> prices[item] ?: 0 }
    }

And finally, let’s assemble the scenario into one suspend function:

suspend fun makeReceipt(order: Order): Receipt {
    val prices = loadPriceList()
    val total = calculateTotal(order, prices)
    return Receipt(orderId = order.id, total = total)
}

Notice: we didn’t create async, we didn’t do await. We don’t need parallelism—we need sequential logic, but different sections must execute “in the right place.”

7. What it looks like in main with runBlocking

From the outside, our code looks almost synchronous, and that’s one reason coroutines are so loved: your brain stops boiling by minute two.

import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val order = Order(id = 1, items = listOf("coffee", "cake"))
    val receipt = makeReceipt(order)

    println("Order #${receipt.orderId}, total=${receipt.total}")
    // Order #1, total=270
}

Here you might catch yourself thinking: “Wait, where is multithreading?” And that’s an excellent question. The answer is: multithreading is not the goal, it’s a tool. Our goal is for I/O and CPU not to interfere with each other and to run in appropriate pools—while keeping the code structure simple.

8. Practical patterns for working with withContext

Keep withContext narrow: it’s a scalpel, not a bucket

In practice, withContext can be used too aggressively: “Let me wrap the whole project in withContext(Dispatchers.IO)—maybe it will help.” Usually this leads to everything getting worse, and you feel like someone treating a cold with molten lead (the effect is noticeable; the benefit is doubtful).

Good discipline looks like this: keep withContext as narrow as possible—only around the place where you truly need another dispatcher.

For example, bad style (an overly wide block mixing different kinds of work):

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

suspend fun makeReceiptBad(order: Order): Receipt =
    withContext(Dispatchers.IO) {
        val prices = loadPriceList()
        val total = order.items.sumOf { prices[it] ?: 0 } // this is already CPU work
        Receipt(orderId = order.id, total = total)
    }

Better—like we did earlier: separate I/O, separate CPU, and leave the rest in “neutral” code.

withContext returns a value: use it for readability

withContext has a very nice feature: it returns whatever the block returned. This helps you write compact code without turning it into a “one-line riddle.”

For example, sometimes it’s convenient to do a “short I/O operation” right at the point of use:

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

suspend fun loadDiscountPercent(): Int =
    withContext(Dispatchers.IO) {
        Thread.sleep(30) // simulation of reading a setting
        10
    }

And then use it in computations:

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

suspend fun applyDiscount(total: Int, discountPercent: Int): Int =
    withContext(Dispatchers.Default) {
        total - (total * discountPercent / 100)
    }

And you again get a readable sequence:

suspend fun makeReceiptV2(order: Order): Receipt {
    val prices = loadPriceList()
    val total = calculateTotal(order, prices)
    val discount = loadDiscountPercent()
    val finalTotal = applyDiscount(total, discount)
    return Receipt(orderId = order.id, total = finalTotal)
}

Yes, there are more functions. But this is the case where “more small functions” is cheaper than “one big function that does absolutely everything.”

Dispatcher inheritance and local override

In coroutines, the idea is important: child actions inherit settings from the parent, including the context. This is one of the building blocks of the structured approach, where coroutines live “inside” managed boundaries.

In practice, this means:

  • if your runBlocking/scope is running on some dispatcher, then launch without an explicit dispatcher will take it;
  • withContext temporarily “overrides” the context for the block and then returns back.

You can imagine it as: “inside one operation we go into another room for a couple of minutes, and then we come back.”

When withContext is better than async/await

Sometimes beginners do this: “I need to compute a value—so async.” But if you need the value right now and parallelism doesn’t provide a benefit, withContext is often simpler and more honest.

Compare two variants.

Variant A: async/await (create a separate coroutine just for the result):

import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope

suspend fun calcTotalAsync(order: Order, prices: Map<String, Int>): Int = coroutineScope {
    val d: Deferred<Int> = async(Dispatchers.Default) {
        order.items.sumOf { prices[it] ?: 0 }
    }
    d.await()
}

Variant B: withContext (sequential, but on the right dispatcher):

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

suspend fun calcTotalWithContext(order: Order, prices: Map<String, Int>): Int =
    withContext(Dispatchers.Default) {
        order.items.sumOf { prices[it] ?: 0 }
    }

The second variant is shorter and, most importantly, more honest in meaning: “we’re not parallelizing, we’re just running the computation where we should.”

9. Typical mistakes when working with withContext and dispatchers

Mistake #1: expecting parallelism from withContext.
It’s very tempting to think: “If I switched to Dispatchers.IO, then now it runs somewhere in parallel, and I’ll continue in the meantime.” But no: withContext does not continue past that point until the block completes. It is specifically about sequential logic. If you need parallelism, that’s a different story—launch a separate coroutine via launch/async.

Mistake #2: making huge blocks inside withContext.
When withContext(Dispatchers.IO) contains “read data,” “parse,” “compute statistics,” and “build a report,” you lose the point of separation. As a result, CPU work starts living in the I/O pool, and then you wonder why everything feels “kind of viscous.” It’s much better to keep withContext narrow, as we did in the examples: one function—one type of work.

Mistake #3: using Dispatchers.IO for computations and Dispatchers.Default for waiting.
It’s like “I fry soup and boil cutlets”—technically something will happen, but the right way is the other way around. Default is usually used for CPU, IO for waiting. If you mix them up, you can get unnecessary contention for threads and unpleasant delays.

Mistake #4: trying to call withContext outside suspend code.
withContext is suspend, and the compiler is your ally here: it doesn’t let you “accidentally” suspend where it’s impossible. If you need to use withContext, the function must become suspend, and the call must happen from a coroutine (for example, from runBlocking or from another suspend function).

Mistake #5: scattering withContext everywhere “just in case.”
If a project develops the habit of “wrapping everything in withContext,” the code becomes noisy and loses clarity: you no longer understand where the real reason for switching is, and where it’s just a “ritual.” withContext is good when it explains the intent: “here is I/O,” “here are computations.” If there’s no intent—don’t add it.

1
Task
Kotlin SELF, level 53, lesson 1
Locked
Shift change
Shift change
1
Task
Kotlin SELF, level 53, lesson 1
Locked
Retry configuration
Retry configuration
1
Task
Kotlin SELF, level 53, lesson 1
Locked
Data and Statistics
Data and Statistics
1
Task
Kotlin SELF, level 53, lesson 1
Locked
Text Normalization
Text Normalization
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION