Jetpack Compose has revolutionized Android UI development by providing a declarative and reactive approach to building user interfaces. One of its key promises is simplicity, but developers often find themselves facing questions about architecture and best practices—one of which is whether to pass ViewModel instances directly into composables.
While it might seem convenient to do so, passing ViewModels into composables can lead to a host of issues that undermine the principles of Compose and modern Android development. In this blog post, we will explore why this practice should be avoided, the potential pitfalls, and better alternatives to ensure clean, maintainable, and testable code.
Understanding Jetpack Compose’s Principles
Before diving into why passing ViewModels in composables is discouraged, it’s essential to understand the core principles of Jetpack Compose:
Declarative UI: Compose uses a declarative approach, where the UI is defined as a function of the current state.
Unidirectional Data Flow (UDF): The flow of data should be predictable and follow a one-way direction—from state to UI.
Separation of Concerns: UI logic should be distinct from business logic to ensure modularity and reusability.
When you pass ViewModels into composables, you risk violating one or more of these principles. Let’s delve deeper into the reasons.
Why Passing ViewModels in Composables is Problematic
1. Coupling UI with Business Logic
ViewModels are primarily designed to encapsulate business logic and serve as the source of truth for UI state. When a ViewModel is passed into a composable, the composable becomes tightly coupled to that specific ViewModel implementation. This makes the composable less reusable and harder to test.
Example of Tight Coupling:
@Composable
fun ProfileScreen(viewModel: ProfileViewModel) {
val profileState = viewModel.profileState.collectAsState()
// UI rendering based on profileState
}Here, ProfileScreen can only function with ProfileViewModel. Reusing this composable in another context without the same ViewModel becomes a challenge.
2. Violating the Separation of Concerns
Composables should focus on rendering UI based on state. When a ViewModel is passed in, it becomes responsible for both state management and UI logic, blurring the lines between these layers. This violates the separation of concerns and makes your codebase harder to maintain.
3. Testing Challenges
Composables that depend on ViewModels are harder to test in isolation. Unit testing composables should involve verifying their behavior based on the input state, not the implementation details of a ViewModel.
Example of a Difficult-to-Test Composable:
@Composable
fun Dashboard(viewModel: DashboardViewModel) {
val data = viewModel.dashboardData.collectAsState()
// Render UI
}Testing the Dashboard composable now requires mocking the DashboardViewModel, adding unnecessary complexity.
4. Lifecycle Management Issues
ViewModels are lifecycle-aware, scoped to their respective ViewModelStoreOwner (e.g., Activity or Fragment). Passing ViewModels into composables can create confusion about their lifecycle, leading to potential bugs such as:
Memory leaks
Unexpected behavior when composables are recomposed or moved across lifecycle boundaries
Better Alternatives to Passing ViewModels
1. Use remember and state hoisting
Instead of passing ViewModels directly, pass the state and event handlers managed by the ViewModel. This keeps the composable independent of the ViewModel while still leveraging its functionality.
Example of State Hoisting:
@Composable
fun ProfileScreen(
profileState: ProfileState,
onEvent: (ProfileEvent) -> Unit
) {
// UI rendering based on profileState
Button(onClick = { onEvent(ProfileEvent.LoadProfile) }) {
Text("Load Profile")
}
}
// ViewModel usage
val profileState by viewModel.profileState.collectAsState()
ProfileScreen(
profileState = profileState,
onEvent = { viewModel.handleEvent(it) }
)This approach keeps ProfileScreen focused on UI rendering and decoupled from the ViewModel.
2. Leverage rememberViewModel
For cases where a composable must access a ViewModel, use hiltViewModel or viewModel() inside the composable to obtain the instance. This ensures the ViewModel lifecycle is properly managed by Compose.
Example:
@Composable
fun DashboardScreen() {
val viewModel: DashboardViewModel = hiltViewModel()
val dashboardState by viewModel.dashboardData.collectAsState()
DashboardContent(dashboardState)
}
@Composable
fun DashboardContent(state: DashboardState) {
// Render UI
}By isolating the ViewModel instantiation to the top-level composable, you avoid passing it down the composable tree.
3. Encapsulate Logic in Use Cases or Repositories
Instead of placing all logic in the ViewModel, delegate it to use cases or repositories. Pass the resulting state to composables.
Example:
val profileState = getProfileUseCase().collectAsState()
ProfileScreen(profileState)This approach promotes a clean architecture and ensures composables remain focused on UI concerns.
Common Questions and Misconceptions
Q: Doesn’t this add boilerplate?
A: While it may seem like additional effort, state hoisting and proper separation of concerns reduce technical debt and improve the maintainability of your codebase in the long term.
Q: What if I need to access ViewModel in deeply nested composables?
A: Use dependency injection tools like Hilt to provide dependencies closer to where they are needed. Alternatively, pass state and event handlers down the tree instead of the entire ViewModel.
Q: Isn’t this overkill for small projects?
A: Even in small projects, following best practices ensures scalability and ease of maintenance as the project grows.
Final Thoughts
Passing ViewModels into composables may seem convenient, but it often leads to tightly coupled, hard-to-test, and error-prone code. By leveraging state hoisting, remember, and clean architecture principles, you can build Compose applications that are modular, testable, and maintainable.
Jetpack Compose encourages developers to think declaratively and embrace unidirectional data flow. Avoiding the direct use of ViewModels in composables is a step towards aligning with these principles and unlocking the full potential of Compose.
By following the strategies outlined in this post, you can ensure your applications are robust, scalable, and developer-friendly.