跪拜 Guibai
← Back to the summary

Stop Obsessing Over Dispatchers: Coroutine Architecture's Real Pillars Are Main-safe, Non-blocking, and Structured Concurrency

When developing Android coroutines, many people easily fall into a misconception: every day they study Dispatchers.IO, Dispatchers.Default, discuss when to use withContext, and when to switch threads. These are certainly important, but I believe they are not the core issues of coroutine architecture. Main-safe, non-blocking behavior, and structured concurrency are the core of the core. Dispatchers are just implementation means; the async contract of APIs and lifecycle management of concurrent tasks are what architecture design should really focus on.

一、不要把调度器当成协程的全部

In many projects you often see code like this:

suspend fun getUser(): User {
    return withContext(Dispatchers.IO) {
        api.getUser()
    }
}

Some people will further discuss: should you use IO or Default here? Actually, this question first requires looking at the implementation of api.getUser(). If it is itself a non-blocking suspend API based on OkHttp, then wrapping it with withContext(Dispatchers.IO) is usually unnecessary. The process of waiting for a network response does not need to continuously occupy a thread.

Consider another example:

withContext(Dispatchers.IO) {
    Thread.sleep(1000)
}

This indeed puts a blocking operation on the IO dispatcher, but it does not eliminate the blocking. The thread is still occupied, just not the main thread. In contrast, delay(1000) suspends the coroutine and releases the current thread, without making the thread wait. These two examples embody two completely different design approaches:

Do not confuse thread switching with non-blocking.

二、Main-safe 才是一个好 API 应该具备的基本契约

I have always believed that the data layer should provide Main-safe APIs. What does that mean? The caller should not care about which thread the API internally needs to execute on. For example:

class UserRepository(
    private val ioDispatcher: CoroutineDispatcher
) {
    suspend fun getUser(): User {
        return withContext(ioDispatcher) {
            legacyBlockingApi.getUser()
        }
    }
}

Here the data layer depends on a blocking API, so it actively switches to the IO dispatcher. The caller completely does not need to care about the internal implementation:

viewModelScope.launch {
    val user = repository.getUser()
}

Even if called from the Main thread, the main thread will not be blocked because of the internal blocking operation. This is Main-safe. Note that suspend does not inherently mean Main-safe. The following code is still unsafe:

suspend fun getUser(): User {
    return legacyBlockingApi.getUser()
}

Although suspend is added, the underlying call is still blocking. So to determine whether an API is Main-safe, you cannot just look at whether it has the suspend modifier; you must look at its actual execution behavior.

Main-safe is the responsibility of the API, not the burden of the caller.

三、优先选择非阻塞 API,而不是习惯性切换线程

Modern Android development already has many mature async APIs. For example:

These APIs already have asynchronous execution capability. There is no need to add withContext(Dispatchers.IO) everywhere just to make the code look more like coroutines. Of course, this does not mean that all IO operations do not need IO. If the underlying layer still has traditional blocking calls, such as file reads/writes, legacy Java SDKs, or blocking database interfaces, you still need to isolate the blocking behavior on an appropriate dispatcher. My principle is simple:

If a non-blocking API can be used, do not proactively introduce blocking; if blocking cannot be avoided, isolate threads in the data layer.

Do not keep pushing thread scheduling responsibility up the layers.

四、数据层应该承担异步能力,而不是让上层负责调度

A mature coroutine architecture should clearly define responsibilities per layer.

Layer Core responsibility
Data Data access, blocking isolation, non-blocking implementation, Main-safe
Domain Business rules, business flow orchestration
Presentation Lifecycle, UI state management

The data layer provides external APIs like:

interface UserRepository {
    suspend fun getUser(): User
    fun observeUser(): Flow<User>
}

Upper layers only need to use these APIs:

viewModelScope.launch {
    repository.getUser()
}

or

repository.observeUser()
    .collect { user ->
        // update UI state
    }

There is no need at every call site to consider: Should I switch here? Should I switch to IO or Default? Can this Repository be called on Main? Could this API block internally? These problems should be solved by the design and implementation of the API. That is why I am not in favor of business layers having lots of code like this:

withContext(Dispatchers.IO) {
    repository.getUser()
}

If the Repository already guarantees Main-safe, this switching is usually redundant.

五、IO 和 Default 的区别,不值得被过度放大

IO and Default do have different design goals. IO is mainly for blocking IO operations; Default is mainly for CPU-intensive computation. They share underlying scheduling resources but have different concurrency scheduling strategies. In real projects, if you call a suspend API that already has non-blocking capability, the actual execution effect may show no clear difference. This does not mean they can be freely interchanged. For a large number of blocking tasks, IO is still the more reasonable choice; for CPU-intensive computation, Default is the more suitable choice. But we should not focus the design of coroutine architecture on which dispatcher to use at each call site.

Dispatcher selection is an implementation problem; Main-safe is an API design problem. The latter has higher priority.

六、结构化并发,才是并发管理的基础

We have discussed Main-safe and non-blocking behavior, but that is not the whole story of coroutine architecture. There is another very important concept: structured concurrency. If Main-safe solves which thread environment an API executes safely in, and non-blocking solves whether the execution occupies a thread, then structured concurrency solves: who creates, who manages, and when concurrent tasks end.

In traditional development, we often see code like this:

class UserRepository {
    fun loadUser() {
        CoroutineScope(Dispatchers.IO).launch {
            // load user
        }
    }
}

It looks like just starting a coroutine, but in fact it creates a task that is detached from the caller's lifecycle. The caller cannot naturally wait for it to complete, nor can it manage it through its own cancellation. This breaks the lifecycle relationship that should exist between concurrent tasks. A more reasonable approach is:

suspend fun loadUser(): User {
    return api.getUser()
}

Then the caller starts the task in its own CoroutineScope:

viewModelScope.launch {
    val user = repository.loadUser()
}

In this way, the task's lifecycle has a clear owner. Further, consider multiple concurrent tasks:

suspend fun loadDashboard(): Dashboard = coroutineScope {
    val user = async {
        userRepository.getUser()
    }

    val orders = async {
        orderRepository.getOrders()
    }

    Dashboard(
        user = user.await(),
        orders = orders.await()
    )
}

Both child tasks belong to the same concurrency scope. The parent scope is responsible for waiting for the child tasks to complete, and cancellation propagates along the parent-child relationship. Under a plain coroutineScope, a child failure also affects the entire scope. This is far more controllable than randomly creating CoroutineScopes and starting coroutines in business code. I believe structured concurrency should become a fundamental principle of modern Android coroutine development. Do not let the data layer start coroutines that detach from the caller's management, and do not let the business layer put together concurrency flows through a bunch of independent scopes.

Concurrent tasks must not only be executable, but also manageable, waitable, and cancellable.

七、协程架构成熟的标志:上层不再关心线程

I think you can observe a few signs of whether a project's coroutine architecture is mature:

First, does the business layer still frequently switch dispatchers?

Second, does the data layer still heavily use blocking APIs?

Third, are there many independent CoroutineScopes that are detached from the caller's lifecycle?

If every call to a Repository requires the caller to decide whether to use IO or Default, that likely means the data layer's responsibility boundary is not clear. If a business operation starts multiple coroutines but cannot clearly define their parent-child relationship, then concurrency management is also problematic. A good design should be:

  1. The data layer prioritizes non-blocking APIs.
  2. The data layer handles thread isolation for blocking operations.
  3. The data layer provides Main-safe suspend / Flow APIs.
  4. Domain is responsible for business orchestration, not underlying thread scheduling.
  5. Concurrent tasks follow structured concurrency, with clear task ownership and lifecycle.
  6. Presentation focuses on lifecycle and UI state, and does not take on thread scheduling responsibility for data access.

Ultimately, upper layers only need to care about business itself. That is the architectural benefit coroutines should bring.


最后

When learning coroutines, you should not spend a lot of time on the minutiae of Dispatchers.IO and Dispatchers.Default. What is worth deep study is:

These questions truly determine the level of coroutine usage in an Android project.

The maturity of coroutine architecture is not that developers become better at switching dispatchers, but that upper-layer business increasingly does not need to care about thread scheduling, and every concurrent task has a clear owner.

Dispatchers are tools, non-blocking is capability, Main-safe is a contract, structured concurrency is order. That is a design direction worth long-term adherence.