Skip to content
Tutorials Center
My learning

Topics

Lesson 56 of 104 ยท App Architecture

Architecture Layers: UI, Domain and Data

Learn the recommended Android app architecture: a UI layer, a data layer and an optional domain layer with use cases, plus separation of concerns and modularization basics.

A first Android app often fits in one file: a composable that calls the network, parses JSON, keeps a list in a variable and draws the result. It works until the second screen needs the same data, the network call must be replaced in a test, or the designer asks for a different layout. Then every change touches everything, because everything knows about everything.

Architecture is the set of rules about which code is allowed to know about which other code. Android's official guidance is simple and has stayed stable for years: a UI layer that shows data and handles input, a data layer that owns the data and business rules around it, and an optional domain layer between them for logic that several screens share. This lesson explains each layer, the rules that connect them and how modules reinforce them. The code that depends on the Android SDK is read-only; the TryIt blocks are runnable stand-ins that build the same layers in plain Kotlin so you can see the shape of the dependencies.

The three layers

flowchart TB
    UI["UI layer<br/>composables + state holders (ViewModel)"]
    DOM["Domain layer (optional)<br/>use cases"]
    DATA["Data layer<br/>repositories + data sources"]
    UI --> DOM
    DOM --> DATA
    UI -. "simple apps may skip the domain layer" .-> DATA

Dependencies point downward: the UI knows the data layer, never the other way around.

The UI layer has two parts. The visible part is your composables (or Views): they render UI state and report events such as clicks. The other part is the state holder, usually a ViewModel, which decides what the state is: it asks the lower layers for data and converts it to something screen-shaped. UI code does not know whether data comes from a network, a database or a file.

The data layer holds the app's data and the rules for working with it. It is built from:

  • Repositories, the public face of the layer. They expose data to the rest of the app, decide whether to read from the cache or the network, and resolve conflicts. The Repository Pattern and Data Sources goes deeper.
  • Data sources, small classes that each wrap one origin: a Retrofit service, a Room DAO, a DataStore file. A data source does one thing and knows nothing about the others.

The domain layer is optional. It contains use cases (also called interactors): small classes with one public operation, such as GetLongReadsUseCase or FormatPriceUseCase. Add them when the same logic would otherwise be copied into several ViewModels, when combining several repositories is complex, or when you want business rules separated from the screen. A small app with one screen per repository does not need them, and adding empty pass-through use cases is a common form of over-engineering.

Principles behind the layers

  • Separation of concerns. A composable should not parse JSON and a repository should not know about Context or colors. Each class has one reason to change.
  • Unidirectional data flow. State flows down from the data layer to the UI; events flow up from the UI. You met this idea in State Hoisting and Unidirectional Data Flow, and the architecture applies it to the whole app.
  • Single source of truth. Each kind of data has exactly one owner that may change it, and everyone else observes it. If two places each keep their own copy of the user's profile, they will disagree.
  • Drive the UI from data models. The state is the truth, the screen is a function of it. Persistent models are preferred over data that lives only in an activity, because they survive restarts.
  • Depend on interfaces at the seams. When a ViewModel takes an ArticleRepository interface, a test can pass a fake, and the app can swap the implementation without touching the UI.

Models at each layer

A frequent beginner question: "should I use the same class everywhere?" Usually not. Each layer has different needs:

Layer Typical model Shaped for
Data source DTO or entity (ArticleDto, ArticleEntity) The wire format or table: nullable fields, snake_case names, string dates
Domain / repository Domain model (Article) What the app means: clean types, no serialization annotations
UI UI model (ArticleRowUi) What the screen shows: formatted strings, ready to draw

Mappers convert between them. The cost is a few small functions; the benefit is that a backend rename changes one mapper instead of fifty composables.

A three-layer sample

The stand-in below builds a miniature feed in the three layers. The "network" is a fake data source behind an interface, the repository maps DTOs to domain models, a use case holds a business rule and the ViewModel-like class turns domain models into UI rows. Nothing in the lower layers refers to the upper ones.

Kotlin UI, domain and data layers with interfaces (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Look at the last function. main plays the role of the composition root, the one place that creates the concrete objects and wires them together. In a real app that job belongs to the Application class or a dependency injection library, which you will meet in Dependency Injection Concepts. Everywhere else, classes only see interfaces and the layer below.

To test LongReadsViewModel, you would pass a use case built on a fake repository with exactly the articles you want. No network, no Android. That is the practical payoff of the layering.

MVC, MVP and MVVM compared

Interviews and older codebases use three acronyms for "how the screen and the logic are split". They are all answers to the same problem, and knowing them explains why the recommended architecture looks the way it does.

  • MVC (Model-View-Controller). The model holds data, the view draws it and the controller handles input. On early Android the Activity ended up being both view and controller: it inflated layouts, read text fields, called the network and updated widgets. The result was the "massive activity": hard to test, because everything needed a device.
  • MVP (Model-View-Presenter). The logic moves into a presenter, a plain class. The view is hidden behind an interface (LoginView with showError(), showLoading()), the activity implements it, and the presenter calls the view to update it. The presenter can be unit-tested with a fake view. The cost is boilerplate (an interface and a presenter per screen), a presenter that holds a reference to a view that dies on rotation, and manual cleanup.
  • MVVM (Model-View-ViewModel). The ViewModel exposes state (observable data); the view observes it and the ViewModel never holds a reference to the view. The view sends events up and receives state down. Because the ViewModel does not know who is watching, it survives rotation and needs no view interface. This is the pattern of ViewModel and the one Android's own guidance builds on.
Topic MVC MVP MVVM
Where the logic lives Activity or controller Presenter (plain class) ViewModel (plain class + ViewModel)
Who updates the view The controller, directly The presenter, through a view interface The view, by observing state
Reference direction Controller knows view Presenter knows view interface ViewModel knows no view
Unit-testing the logic Hard (needs Android) Easy with a fake view Easy: assert on the state
Survives rotation No Only if you design for it Yes (scoped to the screen owner)
Boilerplate Low at first, high later High (contracts) Low

Why MVVM with unidirectional flow won

Three reasons made MVVM the default on Android.

  1. The lifecycle problem. A presenter that calls view.showError() after the view is gone crashes. A ViewModel that only publishes state cannot call a dead view; whoever is currently watching simply sees the latest state.
  2. Compose. In Compose the UI is a function of state, which is exactly what MVVM exposes. There is no view.setText() to call.
  3. Predictability. Plain MVVM can still let the view and ViewModel exchange many separate observable fields, which can contradict each other (isLoading = true and error != null). Unidirectional data flow tightens it: the screen has one immutable state object, events go up as function calls and new state comes down. MVI (Model-View-Intent) takes this to its conclusion by funneling every event through a single onEvent(...) reducer. On Android, "MVVM with a single UiState and unidirectional flow" and "MVI" are close relatives, and either is fine. Choose one and stay consistent, as UI State and One-Time Events describes.

The stand-in builds one tiny screen, a login form with validation, in all three styles so you can compare where the logic lives and how each is tested. The "views" are fake classes that print, because the real ones need Android.

Kotlin One login rule in MVC, MVP and MVVM (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice what each test needs. The MVC controller needs its widgets, the MVP presenter needs a fake view that records calls, and the MVVM test only reads state. A late observer in the MVVM version gets the current state immediately, which is the property that makes rotation harmless. The presenter's detach() is the manual bookkeeping that MVVM removes. These classes are plain Kotlin, so the stand-in is runnable; the real ViewModel base class and lifecycle-aware observation are Android parts, covered in LiveData and Lifecycle-Aware Components and StateFlow and Flow in Compose.

Remember that MVVM describes the UI layer only. It sits inside the three layers above: the ViewModel talks to use cases and repositories, which is where the "Model" of all three acronyms really lives.

Where does each kind of code go?

Use these questions when you are unsure:

  • Does it need Context, a Modifier or a composable? UI layer. (And even there, ViewModels must not hold a Context.)
  • Does it decide what the screen shows, such as loading or error state? The state holder in the UI layer.
  • Does it talk to a network, a file or a database? A data source.
  • Does it decide which source to use or merge two sources? Repository.
  • Is it a business rule used by two screens? A use case, or a repository function if it is about one kind of data.

Modularization overview

A module in Gradle is a separately compiled unit. Splitting a project into modules mirrors the layers and makes the rules enforceable, because a module can only use code from modules it declares as dependencies. Typical splits:

TEXT
app                     the application, navigation host and wiring
feature:feed            the feed screens
feature:search          the search screens
core:data               repositories and data sources
core:model              plain domain models shared by everyone
core:ui                 theme and reusable composables

Benefits include faster incremental builds (only changed modules recompile), clear ownership for teams and the ability to load features on demand. The costs are more build files and a need to design dependencies carefully. For a small app one app module is fine; modularize when builds get slow or teams grow. One rule scales well: features never depend on other features; they depend on core modules, and app is the only place that knows all the features.

The stand-in below checks such rules. Each module has a rank, and a dependency is legal only if it points to a lower rank. That single rule forbids feature-to-feature links, upward links and cycles at once.

Kotlin A module dependency rule checker (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In a real project you can get this kind of guarantee from Gradle itself (a module that is not declared as a dependency cannot be imported) and from lint or architecture tests.

Common mistakes

  • Putting network calls in composables or the activity. They cannot be tested and are repeated on every screen.
  • Using the DTO as the UI model. A backend change then breaks the screens.
  • Use cases that only forward a call. Add the domain layer when it earns its place.
  • Passing Context, Activity or NavController into the data layer. The lower layers must not know about the UI.
  • Letting two classes both write the same data, which breaks the single source of truth.
  • Premature modularization. Start with packages; split into modules when there is a concrete reason.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which direction should dependencies point in the recommended architecture?

    The UI observes and requests data from lower layers; data classes never reference screens, which keeps them testable and reusable.
  2. 2. When is it sensible to add a domain layer with use cases?

    The domain layer is optional. Use cases pay off when they remove duplication or isolate complex rules; pass-through use cases only add noise.
  3. 3. Why map a DTO to a domain model in the repository?

    Mapping isolates the wire format. Nullable fields, odd names and string dates are cleaned up once at the boundary.
  4. 4. What does the single source of truth principle mean?

    With one owner, there is no disagreement between copies. Other layers read and observe; only the owner writes.

Summary

  • The recommended architecture has a UI layer, a data layer and an optional domain layer; dependencies point downward.
  • The UI layer renders state and reports events; a state holder (ViewModel) decides the state.
  • The data layer is made of repositories (the public API) and data sources (one origin each).
  • Use cases belong in the domain layer only when they remove duplication or tame complex rules.
  • Separation of concerns, unidirectional data flow, a single source of truth and interfaces at the seams are the guiding ideas.
  • Keep distinct models per layer (DTO, domain model, UI model) and map at the boundaries.
  • Modules enforce the rules: features depend on core modules, never on each other.
  • The TryIts are plain-Kotlin stand-ins; Android-specific code in this track stays read-only.

Next: ViewModel