跪拜 Guibai
← Back to the summary

AI Makes Code Cheap But Judgment Expensive: The Coroutine Mistakes That Break Android Apps

Code Is Getting Cheaper, Judgment Is Getting More Expensive: Android Architecture and Coroutine Pitfall Guide in the AI Era

AI is changing software development.

In the past, a programmer might spend half a day looking up APIs, trial and error, and tuning threads. Now, just throw the requirement into a dialog box, and AI can generate a seemingly complete set of code in minutes. Architecture that previously took half a day to reason through can now even be accompanied by a polished architecture diagram generated by AI.

Writing code is becoming cheaper and cheaper, so cheap it might as well be free.

But one thing has not become even a bit easier because of this:

Judging what level of code AI has actually produced.

AI is very good at generating something called Local Correctness.

The code compiles. It runs. It even passes unit tests. But when you enthusiastically merge it into the main branch and prepare to accept your boss's praise, it might hand you an ANR, a memory leak, or a concurrency bug that is hard to reproduce.

Why?

Because the truly difficult parts of software development have never been about typing code into an editor, but rather:

These are the questions that really test an engineer's ability.

Today, starting from Android coroutines and architecture design, let's talk about what engineering bottom lines programmers should hold in the AI era.


1. Understanding Coroutines: Don't Treat APIs as a Universal Solution

1. Don't Confuse launch with withContext

In everyday code review, there is a pattern that appears almost everywhere:

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

Many developers have formed muscle memory:

But this actually confuses two concepts: Task Launching and Execution Scheduling.

The core responsibility of launch is to create a new coroutine task, not to switch threads. For example:

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

Here, launch by default inherits the CoroutineContext of viewModelScope. Typically, it executes on the Main Dispatcher.

If the Repository has already handled IO scheduling internally, the caller does not need to specify Dispatchers.IO at all. For example:

class UserRepository(
    private val api: UserApi
) {
    suspend fun getUser(): User {
        return withContext(Dispatchers.IO) {
            api.getUser()
        }
    }
}

Three concepts need to be understood here:

They serve different responsibilities. launch starts a task, while withContext switches the execution context within the current coroutine.

Don't habitually specify Dispatchers.IO at the call site just to execute a suspend function.

2. Whoever Executes Should Be the One to Handle Scheduling

In a healthy Android architecture, the Data layer should have Main-safe capability.

What does Main-safe mean? It means that regardless of whether the caller invokes it on the main thread, the layer guarantees that it will not block the main thread with blocking operations. For example:

class UserRepository(
    private val api: UserApi
) {
    suspend fun getUser(): User {
        return withContext(Dispatchers.IO) {
            api.getUser()
        }
    }
}

The upper layer only needs:

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

The ViewModel does not need to care whether the underlying layer uses synchronous IO, a thread pool, or some other execution mechanism. This is the responsibility boundary.

If every caller needs to know what thread the Repository uses internally, then the implementation details of thread scheduling have already leaked to the upper layer.

There is a viewpoint worth deeply understanding: Main-safe is not just a threading convention; it is an architectural contract that the Data layer provides to its callers.

Callers can invoke on the main thread without knowing whether the underlying operation involves network, database, file IO, or CPU computation. This means the threading model and blocking risks should be encapsulated at the appropriate layer, not scattered as scheduling responsibilities across ViewModels and UseCases.

I have written a dedicated article on this: 👉 "Main-safe: The Real Watershed in Modern Android Architecture"

Thread scheduling should be handled by the layer that does the actual work, not by the layer that initiates the work.


2. Manage Concurrency Well: Don't Let Tasks and Resources Lose Ownership

1. Repository Shouldn't Silently launch

Some code likes to do this:

class UserRepository(
    private val scope: CoroutineScope
) {
    fun loadUser() {
        scope.launch {
            api.loadUser()
        }
    }
}

It looks convenient. The caller just calls loadUser(), and the Repository automatically does the background work. But problems follow:

None of these questions have clear answers in this design. A more natural design is:

class UserRepository(
    private val api: UserApi
) {
    suspend fun loadUser(): User {
        return api.loadUser()
    }
}

Caller side:

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

There is a very important difference here:

suspend is capability; launch is task ownership.

For one-time data operations, the caller should typically decide when to start and when to cancel. When the ViewModel is destroyed, viewModelScope cancels the coroutines it manages, and the cancellation signal propagates downstream. Thus, the task lifecycle has a clear owner.

Of course, the Repository can hold a CoroutineScope in certain cases. For example, app-level data synchronization, WebSocket long connections, or background cache refresh—these tasks may belong to the application lifecycle. The key is not whether the Repository can launch, but:

Does this task belong to the caller, or does it belong to the application itself?

If there is no clear lifecycle ownership, don't casually create a new coroutine scope.

I have previously discussed this: why modern Android architecture prefers Repository to expose suspend fun rather than silently starting launch internally. 👉 "Why Modern Android Officials Prefer Repositories to Expose suspend fun Instead of launch internally"

This article further discusses task lifecycle, cancellation rights, completion timing, and exception boundaries. They seem like coroutine API usage details, but in fact, they determine who controls the work in the architecture.

2. Don't Directly Port Java Blocking Concurrency Models into Coroutines

Kotlin coroutines are not just a new syntax over Java thread pools. They have their own set of concurrency primitives.

For example, the following Java concurrency tools should be used with caution in coroutine business chains:

This is not to say Java concurrency tools are entirely unusable, but you need to understand their execution semantics.

First, look at BlockingQueue:

val queue = LinkedBlockingQueue<String>()

suspend fun consume() {
    val value = queue.take()
    println(value)
}

Although consume is a suspend function, take() still blocks the current thread. This means a coroutine might occupy a thread just to wait for data to appear in the queue. If many coroutines wait in this way, thread pool resources can be consumed.

A better fit for coroutines is Channel:

val channel = Channel<String>()

suspend fun consume() {
    for (value in channel) {
        println(value)
    }
}

When a Channel has no data, the consumer coroutine can suspend without blocking the underlying thread.

Now look at locks. For example:

val mutex = Mutex()

suspend fun update() {
    mutex.withLock {
        // critical section
    }
}

Mutex is a synchronization primitive designed for coroutines. It allows the coroutine to suspend while waiting for the lock, rather than blocking a thread.

Particular attention should be paid to ReentrantLock. It has thread-ownership semantics. If a suspension occurs while holding the lock, the coroutine may resume on a different thread, causing a thread-ownership problem when releasing the lock.

synchronized is not strictly forbidden either. For short, non-suspending critical sections, it still has valid use cases. The key is not to mistake blocking-thread waiting for suspension waiting in coroutines.

3. suspend Does Not Mean Non-Blocking

This is a very easily overlooked issue. Some developers think that adding suspend to a function automatically makes it asynchronous and non-blocking. For example:

suspend fun loadData(): Data {
    Thread.sleep(3000)
    return fetchData()
}

This code is a suspend function, but Thread.sleep still blocks the current thread. suspend only indicates that the function has the ability to suspend; it does not mean that the function internally uses non-blocking operations.

If you are calling a traditional blocking API, you should explicitly isolate the scheduling:

suspend fun loadData(): Data {
    return withContext(Dispatchers.IO) {
        legacyApi.loadData()
    }
}

If you only need to wait for a delay, use:

suspend fun loadData(): Data {
    delay(3000)
    return fetchData()
}

There is an essential difference between the two:

Now consider computation tasks:

suspend fun calculate(): Result {
    return withContext(Dispatchers.Default) {
        heavyCalculation()
    }
}

Asynchrony is an execution capability; non-blocking is a way of using resources. They are not the same concept.

4. Don't Swallow CancellationException

When AI generates code, it often produces exception handling like this:

try {
    repository.load()
} catch (e: Exception) {
    // handle exception
}

It looks fine, but there is a very important control signal hidden: CancellationException.

Coroutine cancellation is not an ordinary business exception; it is a control mechanism in structured concurrency.

Correct approach:

try {
    repository.load()
} catch (e: CancellationException) {
    throw e
} catch (e: Exception) {
    // handle the exceptions that actually need handling
}

In addition, Flow's catch operator has special handling for cancellation exceptions, and you shouldn't simply equate it with a plain try-catch. The key to exception handling is not catching as much as possible to be safe, but being clear about which exceptions should be handled and which control signals must keep propagating.

Don't treat coroutine cancellation as a system failure.


3. Hold the Architecture Boundaries: Don't Let Data and State Lose Order

1. Don't Create a Global Event Bus Just for Communication

Looking back at previous Android projects, EventBus and LocalBroadcastManager were once very common communication methods. For example:

The problem with this approach is that the dependencies are implicit. Page A doesn't know who is listening, and Page B doesn't know where the event comes from. As the business grows, the number of senders and receivers increases, and the whole system can become a communication network that is hard to trace.

In modern Android development, you can choose more explicit communication mechanisms based on different scenarios:

Scenario Recommended Approach
UI persistent state StateFlow
Multi-consumer event broadcast SharedFlow
Single-consumer task passing Channel
Cross-page shared business state Repository + Flow
Fragment communication within the same Activity Shared ViewModel

For example, a ViewModel exposes UI state:

private val _uiState = MutableStateFlow<UiState>(UiState.Loading)
val uiState = _uiState.asStateFlow()

UI layer:

lifecycleScope.launch {
    repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.uiState.collect { state ->
            render(state)
        }
    }
}

Here, the UI doesn't need to manually register and unregister event listeners.

But note that SharedFlow does not natively guarantee that one-time events won't be repeated, nor does it guarantee that events will be received. For example:

private val _events = MutableSharedFlow<UiEvent>(replay = 0)

When there are no active subscribers, events can be lost. If you set replay, new subscribers may receive previous events. So, the design of one-time events needs to consider the number of consumers, lifecycle, replay strategy, and whether the business allows loss.

There is also a common mistake: replace EventBus with a static GlobalEventBus that internally uses MutableSharedFlow, and then send events from anywhere. This doesn't solve the original problem; the underlying tech changed to Flow, but the global implicit dependency still exists.

Technology can be upgraded, but architectural errors won't disappear just because the API changed.

I have also written a dedicated article on event buses, covering UI state, Fragment communication, one-time events, and cross-module state sharing: 👉 "Modern Android Architecture Does Not Need an Event Bus"

2. The Data Layer Should Prefer suspend and Flow

In modern Android projects, the Data layer should try to standardize the expression of asynchronous interfaces. Typically:

For example:

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

This set of interfaces is very clear. Callers don't need to care whether the underlying layer uses Retrofit, Room, or a traditional Callback API. Certain system APIs still use Callback:

fun observeLocation(): Flow<Location> = callbackFlow {
    val callback = object : LocationCallback {
        override fun onLocationChanged(location: Location) {
            trySend(location)
        }
    }
    locationManager.register(callback)
    awaitClose {
        locationManager.unregister(callback)
    }
}

The Callback still exists, but it is encapsulated inside the Data layer and doesn't leak to the upper layers. That is the design we actually want.

What we want to eliminate is not the Callback, but the Callback's intrusion into the upper architecture.

3. The Data Layer Must Handle Exceptions Properly; Don't Let Underlying Exceptions Leak Upward Arbitrarily

This is a problem easily overlooked in layered architecture. Suppose a Repository directly calls Retrofit:

class UserRepository(
    private val api: UserApi
) {
    suspend fun getUser(): User {
        return api.getUser()
    }
}

When a network request fails, the upper layer might receive:

If a ViewModel directly handles these exceptions, it means the ViewModel must understand what network library, database, or SDK the underlying layer uses. This is clearly not an ideal architecture boundary. If the project later switches from Retrofit to another networking implementation, does the ViewModel need to change too?

The Data layer should not only hide the data source, but also hide the exception implementation details of the underlying technology.

A more general architectural principle can be used here:

Don't make callers bear the complexity that is your responsibility; whoever understands the complexity best should bear it.

Network protocols, HTTP status codes, database structures, and cache strategies are all things the Data layer should know. The ViewModel cares about user intent and UI state, not HttpException or SQLiteException.

I discussed this in "Don't Make the Caller Bear Your Complexity — Android Data Layer Design Principles," which also covers problems like exception transparency, thread switching, and data source determination: 👉 "Don't Make the Caller Bear Your Complexity — Android Data Layer Design Principles"

I prefer to split exception handling into three layers:

Layer Main Responsibility
Data Layer Recognize underlying technical exceptions and convert them to stable data-access errors
Domain Layer Express business failures based on business semantics
ViewModel Consume results and map business results to UI states

A few points to note here:

The purpose of the Data layer is not to eliminate exceptions, but to shield underlying technical details so the upper layer doesn't depend on Retrofit, Room, or other specific implementations.

Then look at the Domain layer. The Domain layer should not continue to depend on specific network exceptions; it should decide how to express failure based on business semantics.

Finally, look at the ViewModel:

viewModelScope.launch {
    when (val result = getUserUseCase()) {
        is Result.Success -> {
            _uiState.value = UiState.Content(result.data)
        }
        is Result.Failure -> {
            _uiState.value = UiState.Error(result.error)
        }
    }
}

In this way, the ViewModel doesn't need to know whether the underlying network request threw an IOException or HttpException. It just updates UI state based on the business result.

4. ViewModel Should Not Repeatedly Handle Underlying Exceptions

With the layered design above, let's look at the ViewModel again. Many projects contain code like this:

viewModelScope.launch {
    try {
        val user = repository.getUser()
        _uiState.value = UiState.Content(user)
    } catch (e: IOException) {
        _uiState.value = UiState.Error("Network error")
    } catch (e: HttpException) {
        _uiState.value = UiState.Error("Server error")
    }
}

This code is not syntactically wrong, but it exposes a problem: the ViewModel already knows what underlying network implementation is used.

If multiple ViewModels all write this way, the same exception handling logic is scattered across different screens. This brings several problems:

A more reasonable approach is:

UseCase / Repository converts exceptions into results; ViewModel converts results into UI states.

I have another article dedicated to the boundary of exception handling in ViewModels: 👉 "Why I Don't Directly Handle Exceptions in Android ViewModel?"

5. Data Layer Exposes Cold Flows by Default; Don't Convert to Hot Flows Prematurely

Many developers, when writing a Repository, like to use stateIn or shareIn directly inside. For example:

class UserRepository(
    private val scope: CoroutineScope
) {
    val userFlow = dataSource.observeUser()
        .stateIn(
            scope,
            SharingStarted.Eagerly,
            User()
        )
}

This is not necessarily wrong, but it introduces extra lifecycle and resource management problems. Because stateIn is not just a type conversion; it also means:

For a regular Repository data interface, a more natural way is:

class UserRepository(
    private val dataSource: UserDataSource
) {
    fun observeUser(): Flow<User> {
        return dataSource.observeUser()
    }
}

The ViewModel decides whether to convert to a StateFlow based on the UI's lifecycle:

val userState = repository.observeUser()
    .stateIn(
        viewModelScope,
        SharingStarted.WhileSubscribed(5_000),
        User()
    )

This way, responsibilities are clear:

DataSource  -->  Repository  -->  ViewModel  -->  StateFlow<UiState>  -->  UI

The Data layer is responsible for where data comes from and how it is transformed. The ViewModel is responsible for organizing UI state and lifecycle management.

Of course, the Data layer is not absolutely forbidden from using hot flows. For example:

These scenarios inherently have a clear need for data sharing. Therefore, a more accurate principle is:

Cold flows are the default way to express data; hot flows are a resource management strategy for when there is a clear sharing need.

6. runBlocking: The Bridge Between the Synchronous World and the Coroutine World

Finally, let's discuss a question that often appears in interviews: what is the difference between runBlocking and launch?

In one sentence:

For example:

fun main() {
    runBlocking {
        delay(1000)
        println("Finished")
    }
}

runBlocking is commonly used in ordinary JVM program entry points, test code, and rare scenarios where a synchronous interface must call a suspend function. But in Android, you need to be very careful:

Now look at coroutineScope:

suspend fun loadData() = coroutineScope {
    val a = async { loadA() }
    val b = async { loadB() }
    a.await() to b.await()
}

The biggest difference between the two:

runBlocking is a bridge in the synchronous world; coroutineScope is a structured concurrency container in the coroutine world. Don't treat the bridge as a daily passage.

👉 "Android Interview Series: Where Should runBlocking Actually Be Used?"


4. Code Can Be Generated, Judgment Requires Accumulation

AI can generate large amounts of code in seconds.

But the faster code is generated, the more engineers should pay attention to the issues that simple compilation checks cannot catch:

These are the kinds of judgment that software engineering truly requires.

I have always believed that good architecture is not about using every technology available, nor about abstracting every possibility in advance. It is about clarifying responsibilities, controlling complexity, and ensuring every design has a reason to exist.

AI can help us write code, search information, generate architecture diagrams, and even propose many seemingly good solutions. But ultimately, someone still has to be responsible for the operational results of the system.

Code is getting cheaper, judgment is getting more expensive.

Don't be a copy-paste tool person led around by AI.

Be an engineer who truly understands how systems run, can identify complexity, and dares to say no to unreasonable designs.