Home / Insights / Mobile App Development
Mobile App Development
Android App Architecture with Kotlin Coroutines and Flow: Patterns for Maintainable Apps
Coroutines and Flow make asynchronous Android code readable, but they do not make it maintainable on their own. This guide sets out the architectural patterns, scope rules and testing habits that stop a growing Kotlin codebase from turning into a tangle of leaked jobs and duplicated state.
Key takeaways
- Use suspend functions for one-shot work and Flow for data that changes over time; keep that rule consistent across every repository.
- Expose one immutable UI state per screen from the ViewModel, and reduce one-off events such as snackbars and navigation triggers to state rather than streaming them.
- Scope ownership is an architectural decision: viewModelScope for screen work, an injected application scope for work that must outlive a screen, and never GlobalScope.
- Inject dispatchers and scopes so that tests run deterministically with virtual time; untestable coroutine code is usually a design smell, not a testing problem.
- Adopt the patterns incrementally, starting with the screens that change most often, and enforce them with code review checklists and lint rules.
On this page
- Why coroutines alone do not give you a maintainable app
- What layering and data flow pattern should you standardise on?
- StateFlow, SharedFlow, cold Flow or Channel: which should you use?
- Where should coroutines be launched, and who owns their lifetime?
- How should errors and cancellation be handled?
- How do you test coroutine and Flow code reliably?
- How do you move an existing app to these patterns?
- Code review checklist for coroutine and Flow architecture
- Frequently asked questions
- Sources and methodology
Most Android teams adopted Kotlin coroutines because callbacks and RxJava chains were hard to read. The readability gain is real. The maintainability gain is not automatic. We regularly review codebases where coroutines are launched from Fragments, repositories expose MutableStateFlow to anyone who asks, exceptions disappear inside catch (e: Exception) blocks that also swallow cancellation, and every screen has its own home-grown pattern for loading and error states. The app works, but each new feature costs more than the last.
This article is for CTOs, engineering managers and senior Android developers who own a Kotlin codebase that is expected to live for years. It explains which layering and state patterns hold up, how to choose between the main Flow types, where coroutine scopes should live, how to handle errors and cancellation, and how to test all of it. It finishes with a migration plan and a review checklist. The guidance follows Google’s own architecture and coroutine recommendations, with our commentary on where teams most often go wrong. If you need extra hands to apply it, our Android developers work in Kotlin, Jetpack Compose, coroutines, Room, Retrofit and Hilt inside your existing backlog.
Why coroutines alone do not give you a maintainable app
Coroutines solve a syntax problem: they let asynchronous code read like sequential code. They do not answer the structural questions that decide whether an app is cheap or expensive to change. Who owns this piece of data? Which component is allowed to modify it? What happens to in-flight work when the user rotates the device or leaves the screen? Where do errors end up?
Google’s guide to app architecture calls separation of concerns the most important principle and describes writing all your code in an Activity as a common mistake. It recommends at least two layers, a UI layer and a data layer, with an optional domain layer used only when it simplifies or reuses logic. Coroutines and Flow are the plumbing between those layers. When the layers are unclear, the plumbing spreads everywhere.
Symptoms that the architecture is the problem
- State is duplicated. The same list lives in a Room table, a repository cache and a ViewModel field, and they disagree after a refresh.
- Bugs appear after rotation or process death. Work restarts, results are lost, or a dialog shows twice.
- Tests are slow or flaky. Tests rely on real delays or
Thread.sleepbecause dispatchers are hard-coded. - Crashes trace back to the background. A collector keeps updating a view that is no longer visible.
- Every screen is different. New developers cannot predict where loading, error and empty states are handled.
Each symptom maps to a missing rule rather than a missing library. The rest of this article sets out those rules.
What layering and data flow pattern should you standardise on?
The pattern that holds up best in long-lived apps is unidirectional data flow (UDF) built on a single source of truth (SSOT) per data type. Google’s guide describes UDF as state flowing in one direction and events that modify data flowing in the opposite direction. The SSOT is the only component allowed to mutate a given piece of data, and it exposes that data through an immutable type.
A practical layer contract
| Layer | Owns | Exposes | Must not |
|---|---|---|---|
| Data sources | One source each: Room DAO, Retrofit service, DataStore | Suspend functions and cold Flows | Know about screens or ViewModels |
| Repositories | The SSOT for a data type, merging sources and caching policy | Suspend functions for one-shot calls, Flow for observable data | Expose mutable state or choose UI dispatchers |
| Domain (optional use cases) | Reusable business rules that combine repositories | A single operator function, suspend or Flow | Hold state of their own |
| ViewModel (state holder) | Screen state and business-logic coroutines | One immutable StateFlow of UI state, plus event functions | Reference Views, Context or navigation controllers |
| UI (Compose or Views) | Rendering and UI logic such as navigation | Callbacks for user events | Launch business-logic coroutines |
The coroutine-specific rule underneath this table comes from Google’s coroutines best practices: the data and business layers should expose suspend functions for one-shot calls and Flow for data that changes over time. That one convention removes a surprising amount of debate. A getInvoice(id) call that fetches once is a suspend function. An observeInvoices() stream that updates when the database changes is a Flow. Nothing in those layers returns a callback, a LiveData or a mutable flow.
Offline-first changes the SSOT
For apps that must work with patchy connectivity, such as field service or care apps, the guide notes the SSOT is typically the database. The repository writes network results into Room and the UI observes the Room Flow. This is the most robust pattern we know for keeping screens consistent, because there is exactly one place where data changes and every observer sees the same result.
StateFlow, SharedFlow, cold Flow or Channel: which should you use?
Choosing the wrong stream type is the most common source of subtle bugs we see. The choice is easier when tied to the question each type answers.
| Type | Hot or cold | Best for | Watch out for |
|---|---|---|---|
Cold Flow | Cold: runs per collector | Repository and DAO streams, transformations | Each collector re-runs the producer, so share it if several screens collect |
StateFlow | Hot, always has a value | Screen UI state exposed by a ViewModel | Conflated: fast updates can skip intermediate values |
SharedFlow | Hot, configurable replay and buffer | Broadcasting app-wide signals to several collectors, such as session expiry | Values emitted with no subscribers are lost unless replay is configured |
Channel | Hot, single consumer | Internal work queues inside a component | No delivery guarantee to UI when the consumer is not active |
According to Android’s StateFlow and SharedFlow documentation, StateFlow is a state holder that requires an initial value and emits the current state to each new collector, while SharedFlow is a configurable generalisation with replay, buffer overflow policies and a subscription count. The same page explains stateIn and shareIn, which convert a cold Flow into a hot one using a scope and a SharingStarted policy.
The default ViewModel pattern
For most screens, the cleanest pattern is to combine repository Flows and convert them with stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initialState). The timeout keeps the upstream active for a few seconds after the last collector disappears, so a configuration change does not restart the database query or network call, while a user leaving the app still stops the work. Use a private MutableStateFlow backed by a public read-only StateFlow only when the ViewModel needs to hold state that does not come from a repository, such as form input.
One-off events belong in state
Many teams expose snackbars and navigation as a Channel or SharedFlow. Google’s guidance on UI events advises against this: when the ViewModel outlives the UI, these streams do not guarantee the event is delivered and processed. The recommended approach is to reduce the event to UI state, for example a nullable userMessage field, and have the UI call back to the ViewModel once it has shown the message. This feels more verbose at first. In practice it removes a class of lost-message and double-navigation bugs, and it makes the behaviour testable by asserting on state.
Where should coroutines be launched, and who owns their lifetime?
Structured concurrency means every coroutine has an owner, and when the owner is cancelled its children are cancelled too. In an Android app, deciding the owner is an architectural decision, not an implementation detail.
Scope rules we apply on every project
- ViewModels launch business-logic work in
viewModelScope. The coroutines best practices page recommends ViewModels create coroutines and expose observable state rather than suspend functions, and notes that work inviewModelScopesurvives configuration changes. - The UI collects, it does not launch business logic. In Compose, collect UI state with lifecycle awareness. In the View system, wrap collection in
repeatOnLifecycle(Lifecycle.State.STARTED). The StateFlow documentation warns that a barelaunchorlaunchInkeeps processing events while the view is not visible, which can lead to crashes. - Repositories use
coroutineScopeorsupervisorScopefor work tied to the caller. Parallel fetches inside a single operation should be cancelled if the caller goes away. - Work that must outlive a screen uses an injected application scope. Examples include saving a draft after the user presses back, or completing an upload already in progress. Inject this scope through Hilt so it can be replaced in tests.
- Work that must survive process death goes to WorkManager. No coroutine scope survives the operating system killing your process.
- No
GlobalScope. The best practices page lists it as something to avoid because it hard-codes the scope and makes testing difficult.
Dispatchers: inject, do not hard-code
Suspend functions should be main-safe, meaning callers can invoke them from the main thread without blocking it. The function that does blocking work is responsible for moving to Dispatchers.IO or Dispatchers.Default with withContext. Pass those dispatchers in through the constructor rather than referencing them directly. This is the single change that most improves testability, because tests can swap in a test dispatcher and control virtual time.
How should errors and cancellation be handled?
Unclear error handling is where coroutine code most often goes from tidy to fragile. Three rules cover most cases.
1. Catch specific exceptions where you can act on them
The best practices page recommends catching expected exceptions inside coroutines launched in viewModelScope or lifecycleScope, and catching specific types such as IOException rather than Exception or Throwable. Catching everything hides programming errors that should crash in development and be reported in production.
2. Never swallow cancellation
Cancellation in coroutines is cooperative and is signalled with CancellationException. If a broad catch block absorbs it, the coroutine keeps running after its owner has gone, which leaks work and can update stale UI. The guidance is to never swallow it, or always rethrow it if caught. Long-running loops and CPU-bound work should check ensureActive() so they respond to cancellation promptly.
3. Model failure in the UI state, not in a side channel
Represent loading, content, empty and error as part of the screen’s state, typically a sealed interface or a data class with explicit fields. Repositories can return a result wrapper for operations that commonly fail, such as network calls, but keep the wrapper consistent across the codebase. A mix of nullable returns, thrown exceptions and custom result types is harder to review than any single choice.
How do you test coroutine and Flow code reliably?
Well-structured coroutine code is easy to test. If a team says its coroutine tests are slow or flaky, the root cause is usually hard-coded dispatchers, real delays, or collectors that never end. Our guide to flaky tests covers the wider problem; the coroutine-specific techniques are below.
Testing toolkit
runTestwith test dispatchers. The best practices page recommends injectingStandardTestDispatcherorUnconfinedTestDispatcherand sharing one scheduler, so tests run deterministically with virtual time.- Fakes over mocks for data sources. Android’s guide to testing Kotlin flows recommends replacing a consumed Flow with a fake that emits controlled values.
- Terminal operators for simple assertions.
first(),toList()andtake(n)cover finite flows. backgroundScopefor continuous collection. Collecting a never-ending flow inbackgroundScopeensures it is cancelled when the test ends; otherwiserunTestwaits for a flow that never completes.- Assert on
.valuefor StateFlow. Because StateFlow is conflated, the guide recommends asserting current state rather than every emission. If the StateFlow was built withstateInandWhileSubscribed, start an empty collector first, or the value never updates.
A useful rule of thumb: if a ViewModel test needs more than a few lines of setup to control timing, the ViewModel is probably doing work that belongs in a repository or use case.
How do you move an existing app to these patterns?
Few teams have the luxury of starting fresh. A rewrite is rarely justified for architectural hygiene alone; incremental migration delivers most of the benefit with far less risk.
Step-by-step migration
- Write the conventions down. One page covering the layer contract, Flow type choices, scope rules and error handling. Agree it in a short architecture review.
- Introduce dispatcher and scope injection first. It is low risk, touches many files mechanically and makes everything after it testable.
- Pick the three screens that change most often. Migrate them to a single immutable UI state and
stateIn. These are where maintainability pays back fastest. - Convert repositories as you touch them. Replace callbacks and LiveData with suspend functions and Flow. Room and Retrofit both support these natively.
- Remove event channels. Replace them with state fields and acknowledgement callbacks, adding tests for each.
- Enforce in review and CI. Add lint checks or Detekt rules for
GlobalScope, hard-coded dispatchers and exposed mutable flows.
Pair the migration with performance and security work you may already be planning, such as the measures in our articles on Android app size and startup time and Play Integrity and app hardening. Refactoring the data layer is a good moment to revisit how much work runs at startup.
Costs and risks to plan for
- Temporary inconsistency. For a period, old and new patterns coexist. Mark legacy modules clearly so new code does not copy them.
- Learning curve. Structured concurrency and cancellation semantics take time to absorb; budget for pairing and review time, not just coding.
- Behaviour changes. Moving from LiveData to StateFlow changes lifecycle behaviour, because LiveData stops observing automatically while flows need lifecycle-aware collection. Regression test the migrated screens.
- Over-engineering. Adding use cases and modules everywhere slows small teams down. Keep the domain layer optional, as Google’s guide suggests.
Code review checklist for coroutine and Flow architecture
Use this checklist in pull request reviews and when assessing an inherited codebase or a new hire’s work.
- Does each data type have one owner that alone can modify it?
- Do repositories expose suspend functions for one-shot work and Flow for observable data, with no mutable types leaking out?
- Does each screen expose a single immutable UI state, including loading, empty and error?
- Are one-off events such as messages and navigation triggers modelled as state with an acknowledgement?
- Is every coroutine launched in an owned scope, with no
GlobalScope? - Is UI collection lifecycle-aware?
- Are dispatchers and long-lived scopes injected rather than referenced directly?
- Are exceptions caught by specific type, and is
CancellationExceptionalways rethrown? - Do loops and CPU-bound work check for cancellation?
- Do ViewModel tests use test dispatchers and assert on state, without real delays?
- Is work that must survive process death handed to WorkManager?
If you are hiring to strengthen an Android team, ask candidates to walk through a short ViewModel and repository and find the problems against this list. It reveals far more than questions about syntax.
Frequently asked questions
Should we still use LiveData in new Android code?
LiveData still works, but for new Kotlin code we recommend StateFlow for UI state, because it fits naturally with coroutines and Flow operators in the data layer. The main difference to manage is lifecycle: LiveData stops observing automatically, whereas Flow collection must be wrapped in lifecycle-aware APIs.
Do we need a domain layer with use cases?
Not always. Google’s architecture guide describes the domain layer as optional. Add use cases where business rules are shared across screens or are complex enough to deserve their own tests; skip them where they would only forward calls to a repository.
Is it safe to expose one-off events with SharedFlow or Channel?
It is common but risky. Google’s UI events guidance warns these streams do not guarantee delivery when the ViewModel outlives the UI. Modelling the event as state, with the UI acknowledging it once shown, is more reliable and easier to test.
How long does it take to migrate an existing app to these patterns?
It depends on size and current state, so we avoid generic estimates. Most teams can introduce dispatcher injection and convert the most-changed screens within normal feature work, then convert remaining repositories as they are touched rather than in a single project.
What should we test for when hiring Android developers for coroutine-heavy apps?
Ask candidates to explain scope ownership, cancellation and the difference between StateFlow and SharedFlow, then review a small flawed ViewModel. Strong candidates spot swallowed cancellation, hard-coded dispatchers and leaked mutable state quickly.
Sources and methodology
Guidance reflects PoliteTech delivery experience. The external references below informed specific points in this article.
- Android Developers: Guide to app architecture — accessed 9 November 2026. Separation of concerns, recommended UI and data layers, optional domain layer, single source of truth and unidirectional data flow.
- Android Developers: Best practices for coroutines in Android — accessed 9 November 2026. Dispatcher injection, main-safe suspend functions, ViewModel-owned coroutines, suspend versus Flow in data layers, avoiding GlobalScope, cancellation and exception handling.
- Android Developers: StateFlow and SharedFlow — accessed 9 November 2026. Differences between StateFlow and SharedFlow, stateIn and shareIn, repeatOnLifecycle and comparison with LiveData.
- Android Developers: UI events — accessed 9 November 2026. Reducing ViewModel one-off events to UI state and the delivery risks of Channels and other streams.
- Android Developers: Testing Kotlin flows on Android — accessed 9 November 2026. Fake producers, backgroundScope collection, asserting StateFlow value and testing stateIn with WhileSubscribed.
Related reading
Continue your research
Is your Android codebase getting harder to change with every release?
We can review your coroutine and Flow architecture, or add Kotlin developers who apply these patterns inside your existing team.
