Clean Architecture: Use Cases in Android
Table of Contents
🎯 The Role of the Use Case
In Clean Architecture, the Use Case (Interactor) encapsulates a single, specific business rule. It sits between the ViewModel (Presentation) and the Repository (Data).
Why Do We Need It?
- Reusability:
GetUserProfilecan be called fromProfileViewModel,SettingsViewModel, andOrderViewModel. - Testability: Testing pure business logic without mocking ViewModels or Repositories.
- Encapsulation: Hides complex data fetching logic (e.g., fetch from API, save to DB, transform data) from the UI.
🏗️ Implementation Structure
A Use Case should do one thing and do it well.
1. Functional Interface (Invoke Operator)
By overriding operator fun invoke, the Use Case can be called like a function.
class GetUserUseCase @Inject constructor(
private val userRepository: UserRepository
) {
operator fun invoke(userId: String): Flow<Result<User>> {
return userRepository.getUser(userId)
.map { ... } // Transform data for UI if needed
}
}
2. ViewModel Usage
The ViewModel injects the Use Case, not the Repository.
@HiltViewModel
class ProfileViewModel @Inject constructor(
private val getUserUseCase: GetUserUseCase
) : ViewModel() {
fun loadProfile() {
getUserUseCase("123").collect { ... }
}
}
⚠️ Common Pitfalls
- Anemic Use Cases: A Use Case that just forwards the call to Repository.
- Is it bad? Not necessarily. It maintains consistency. But if 90% are anemic, consider skipping Use Cases for simple CRUD.
- God Use Cases:
UserManagerUseCasehandling login, logout, profile, settings. Split it up!
🏁 Conclusion
Use Cases are the “verbs” of your application (Login, GetProfile, BuyItem). They define what your app does, independent of how it shows it or where it stores data.
You might also be interested in
MVVM: The View Layer Guide
How to implement the View layer in MVVM with Jetpack Compose. State collection, error handling, and separation of concerns.
MVVM Model: The Invisible but Vital Data Layer
The 'Model' in MVVM is much more than data classes. Learn to design a robust model layer that survives UI and backend changes.
SOLID Principles: Android Examples
Understanding SOLID principles in modern Android. Examples using Kotlin, Hilt, and MVVM.