Domain layer and use cases
Why it matters
- Google's app architecture guide lists the domain layer as optional. Senior interviewers ask why you added use cases, not just how. Knowing when to skip them shows judgment.
- A business rule like "a user must have a display name" written in three ViewModels drifts apart over time. A use case gives a shared rule one home that every screen calls.
- Use cases keep ViewModels small: the ViewModel turns results into UI state, and the use case holds the rule. Both are easy to unit test on the JVM.
- In modularized apps (see the modularization lesson), a
:core:domainmodule is a common place for use cases. Getting its dependency direction right avoids cycles between domain and data modules.
The simple explanation
- A restaurant kitchen has a recipe card (use case): "check the steak is cooked, plate it, add garnish".
- The pantry staff (repository) fetch and store ingredients; the recipe card says what to do with them.
- Several dishes can share one recipe card for the same sauce, so the sauce tastes the same everywhere.
- For a glass of water you skip the recipe card and just pour it. That is skipping the domain layer for trivial flows.
What is the domain layer in Android? It is an optional layer between the UI layer and the data layer that holds use cases: classes that each perform one business operation, such as GetUserUseCase or FormatPriceUseCase. Google's guide recommends it for logic that is complex or reused by several ViewModels. Domain models (plain Kotlin data class types with no Room or JSON annotations) often travel with it, though many apps define their models in the data layer instead.
A use case usually has one public operator fun invoke, so the caller writes getUser(id). It is a stateless class that gets its repositories through the constructor and is created per caller (it has no lifecycle of its own). Google's guide names them verb + noun + UseCase and says they should be main-safe, like repositories.
Errors. A use case can let exceptions propagate (the ViewModel catches them), return Kotlin's Result<T>, or return a custom sealed type such as GetUserResult.NotFound. A sealed type is the most explicit; Result is lighter. If you use runCatching in a suspend function, remember it also catches CancellationException, which breaks coroutine cancellation, so rethrow it.
Dependency direction. In Google's layering the domain layer depends on the data layer: use cases call repositories. In Clean Architecture style the domain declares repository interfaces and the data layer implements them, so the domain depends on nothing. Both work; pick one per codebase.
| Concern | Domain layer | Data layer |
|---|---|---|
| Models | Plain data class User (no annotations) | Room @Entity, network DTOs |
| Logic | Business rules, combining repositories | Network calls, database queries, caching, mapping |
| Dependencies | Repositories, or nothing in Clean style | Retrofit, Room, DataStore |
| Typical tests | JVM unit tests with fake repositories | JVM tests with fakes; DAO tests on Robolectric or a device |
When to skip it. If the use case would only call repository.getUser(id) and return the result, it is a pass-through: let the ViewModel call the repository. Google's guide is explicit that the domain layer is optional.
Flow use cases. A use case that returns a Flow should usually be cold: it transforms the repository Flow with map or combine, and the ViewModel turns it into state with stateIn(viewModelScope, ...). Upstream errors need the catch operator; mapping inside map only covers errors thrown in that lambda.
Notes
- Google's architecture guide marks the domain layer as optional. Add use cases for complex or reused logic, not for every repository call.
- Name use cases verb + noun +
UseCase(GetUserUseCase,FormatPriceUseCase) and give each oneoperator fun invokeso call sites readgetUser(id). - Use cases are stateless and get repositories through the constructor. They do not need to be singletons.
- A domain model is a plain Kotlin
data class. If it carries@Entityor@SerializedName, a database or JSON detail has leaked into it. - Use cases must be main-safe. Room and Retrofit suspend functions already are; add
withContextwith an injected dispatcher only for CPU-heavy work such as sorting a large list. runCatchinginside a suspend function also catchesCancellationException. Rethrow it, or catch only the exceptions you expect, such asIOException.- In a
Flowuse case, thecatchoperator handles upstream exceptions; atryinsidemaponly covers that lambda. Aftercatchemits, the flow completes. - With Hilt, a use case with an
@Inject constructorneeds no module. Repository interfaces are bound to implementations with@Binds. - If the domain module is a plain Kotlin (
kotlin("jvm")) module, Android and Room classes cannot even be imported there, which enforces the boundary for free. - Keep UI state types (
UiState,Loading,Errorfor screens) out of the domain layer. The ViewModel maps domain results to UI state.
Code example
This shows a domain model, a repository interface, and two use cases: a suspend one that returns Result and a Flow one that adds a business rule to a repository stream.
import java.io.IOException
import javax.inject.Inject
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
// domain/model/User.kt
data class User(
val id: String,
val displayName: String,
val email: String,
)
// UserRepository.kt (in the domain module in Clean style, in the data module in Google's style)
interface UserRepository {
suspend fun getUserById(id: String): User?
fun observeUser(id: String): Flow<User>
}
class UserNotFoundException(id: String) : Exception("User $id not found")
class MissingDisplayNameException(id: String) : Exception("User $id has no display name")
// domain/usecase/GetUserUseCase.kt
// Business rule: a user without a display name is not usable by the app.
class GetUserUseCase @Inject constructor(
private val repository: UserRepository,
) {
suspend operator fun invoke(id: String): Result<User> =
try {
val user = repository.getUserById(id) ?: throw UserNotFoundException(id)
if (user.displayName.isBlank()) throw MissingDisplayNameException(id)
Result.success(user)
} catch (e: CancellationException) {
throw e // never swallow cancellation
} catch (e: Exception) {
Result.failure(e)
}
}
// domain/usecase/ObserveDisplayNameUseCase.kt
// Cold Flow: each collector gets its own upstream collection.
class ObserveDisplayNameUseCase @Inject constructor(
private val repository: UserRepository,
) {
operator fun invoke(id: String): Flow<Result<String>> =
repository.observeUser(id)
.map { user ->
if (user.displayName.isBlank()) Result.failure(MissingDisplayNameException(id))
else Result.success(user.displayName.trim())
}
.catch { e ->
if (e is IOException) emit(Result.failure(e)) else throw e
}
}GetUserUseCaseturns "not found" and "blank name" intoResult.failure, but rethrowsCancellationExceptionso leaving the screen still cancels the work.ObserveDisplayNameUseCaseapplies the rule withmap; thecatchoperator turns an upstreamIOExceptioninto a value. Other exceptions are rethrown so real bugs are not hidden.- Both classes are stateless and use
@Inject constructor, so Hilt can create them without a module. - In the ViewModel,
observeDisplayName(id).map { it.toUiState() }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), UiState.Loading)gives the screen state that stops collecting when nobody is watching.
Run the idea in plain Kotlin
An in-memory repository stands in for the data layer. The use case applies the rule and returns Result, and the last call shows that cancellation is not swallowed.
import kotlinx.coroutines.*
data class User(val id: String, val displayName: String, val email: String)
interface UserRepository {
suspend fun getUserById(id: String): User?
}
class InMemoryUserRepository(private val users: Map<String, User>) : UserRepository {
override suspend fun getUserById(id: String): User? {
delay(50) // stands in for a database read
return users[id]
}
}
class GetUserUseCase(private val repo: UserRepository) {
suspend operator fun invoke(id: String): Result<User> =
try {
val user = repo.getUserById(id) ?: throw NoSuchElementException("User " + id + " not found")
require(user.displayName.isNotBlank()) { "User " + id + " has no display name" }
Result.success(user)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Result.failure(e)
}
}
fun main() = runBlocking {
val repo = InMemoryUserRepository(
mapOf(
"1" to User("1", "Alice", "alice@example.com"),
"2" to User("2", " ", "bob@example.com"),
)
)
val getUser = GetUserUseCase(repo)
println("User 1 -> " + getUser("1").getOrNull()?.displayName)
println("User 2 -> " + getUser("2").exceptionOrNull()?.message)
println("User 99 -> " + getUser("99").exceptionOrNull()?.message)
// The caller leaves the screen while the read is in progress
val job = launch { println("never printed: " + getUser("1")) }
delay(10)
job.cancel()
job.join()
println("Cancelled job finished, isCancelled = " + job.isCancelled)
}Expected output:
User 1 -> Alice
User 2 -> User 2 has no display name
User 99 -> User 99 not found
Cancelled job finished, isCancelled = true
In production
- To "avoid duplicate queries", a team made
ObserveUserUseCasea singleton that converted the repository Flow into aStateFlowwithstateIn(appScope, SharingStarted.Eagerly, null). - The upstream Room query was never cancelled. After users left the profile screen, every write to the users table still re-ran the query and the mapping, on every user id that had ever been opened.
- Profiling showed steady CPU work on the profile query while the user was on unrelated screens.
- The use case went back to being a stateless class that returns a cold
Flow(mapover the repository Flow). - Each ViewModel turns it into state with
stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), initial), so collection stops a few seconds after the screen goes away and ends when the ViewModel is cleared. - A test collects the use case in a child coroutine, cancels it, then writes to the fake repository and asserts the mapping did not run again.
- A developer added
@Entity(tableName = "users")to the domainUserclass to "save a mapping step". - The domain module had to add a Room dependency, and the table schema became the model every screen used.
- Weeks later a migration renamed a column, and the change rippled through use cases, ViewModels and Compose previews.
- The team removed the annotation and created a separate
UserEntityin the data module, withtoDomain()andtoEntity()mappers next to the repository. - They turned the domain module into a plain Kotlin (
kotlin("jvm")) module, so any import ofandroidx.roomthere now fails to compile.
Common mistakes
- Pass-through use case. A use case that only calls
repository.getUser(id)and returns the result adds a file and a hop with no logic. Let the ViewModel call the repository until there is a rule to extract. runCatchingaround suspend calls. It catchesCancellationExceptiontoo, so a cancelled coroutine keeps going and returns a failure instead of stopping. RethrowCancellationException, or catch specific exceptions.- Mapping errors only inside
map. AtryorrunCatchinginsidemapdoes not see exceptions thrown by the upstream Flow. Use thecatchoperator for upstream errors, or let them reach the ViewModel. - Framework annotations on domain models.
@Entity,@SerializedNameor@ColumnInfoon a domain model ties every layer to the database or the JSON shape. Keep domain models plain and map in the data layer. - UI state in the domain layer. A
sealed class UiStatewithLoadingandErrorin the domain module makes the domain know about screens. Return domain results; the ViewModel maps them to UI state. - Stateful or app-scoped use cases. Caching a
StateFlowinside a singleton use case keeps its upstream running for the process lifetime. Keep use cases stateless and letviewModelScopecontrol collection.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“Why would you add a domain layer to an Android app?”
“When is a domain layer NOT worth it?”
“How do you test a use case that returns a Flow?”
“What is the difference between a use case and a repository method?”
Quiz
What is a domain model in an Android app?
When should you skip the domain layer?
A suspend use case wraps its repository call in runCatching. What is the problem?
A use case returns repository.observeUser(id).map { ... }. Where should errors thrown by the upstream repository Flow be handled?
0 of 4 answered
Mini task
Add a use case for one business rule (20 min)
You have a UserRepository and a UserViewModel that calls it directly. Extract one rule into a use case.
- Check that there is a rule. Find a check that two ViewModels (or one ViewModel and a worker) both perform, such as "display name must not be blank". If there is none, stop: you do not need a use case yet.
- Create the domain model. Add
data class User(val id: String, val displayName: String, val email: String)with no annotations. - Write the use case. Create
GetUserUseCasewithsuspend operator fun invoke(id: String): Result<User>. Return a failure for a missing user and for a blank display name. RethrowCancellationException. - Update the ViewModels. Replace the duplicated checks with
getUser(id). Map success toUserUiState.Loadedand failure toUserUiState.Error. - Write JUnit tests. Use
runTestand a fakeUserRepository. Assert that a blankdisplayNamegivesResult.failureand that a missing user givesResult.failurewith your not-found exception. - Verify the boundary. If your use case lives in a plain Kotlin module, run
./gradlew :core:domain:test; in an Android library module, run./gradlew :core:domain:testDebugUnitTest.
Done condition: the rule exists in exactly one place, both callers use the use case, and the tests pass on the JVM without Robolectric.