Skip to content

Mistakes when using ViewModels

ViewModels helps manage UI data. If not used correctly, it can lead to problems that make your app complex and hard to manage. In this article, I explore frequent mistakes developers make when using ViewModels

Using Android dependencies

One common issue when building Android apps is adding Android-specific code right into the ViewModel. This practice makes it tough to test the ViewModel separately from the Android operating system. Since the ViewModel is too connected to Android, any changes or tests become more complicated and less reliable.

Instead, it’s smarter to design ViewModels that don’t depend on Android code. By keeping the ViewModel clean of these dependencies, your code becomes easier to manage. This separation helps in testing different parts of your app independently, which is crucial for finding and fixing bugs quickly.

Not being testable

A ViewModel in Android should be designed for easy testing, but developers often create ViewModel code that relies too much on the Android framework, which complicates testing. To improve the testability of a ViewModel, it’s beneficial to implement dependency injection. This technique allows you to introduce necessary components and interfaces into your ViewModel, enabling you to use mock dependencies during testing.

By using mocks, you can simulate various scenarios and interactions, ensuring that the ViewModel behaves as expected without needing the actual Android framework during tests.

Exposing mutable state

When developing ViewModels in Android, it’s important not to expose mutable LiveData or state objects directly. This is because external classes can change these objects, leading to unpredictable user interface behaviors.

To avoid this, you should encapsulate any mutable state within the ViewModel itself and only expose immutable versions of LiveData or state objects. This practice ensures that the state can only be modified internally within the ViewModel, maintaining stability and predictability in the UI.

Initializing state in the init block

Initializing ViewModel state directly in the init block can make your app’s state management inflexible and difficult to manage, particularly if initialization relies on external settings or parameters.

A more effective method involves using factory methods or dependency injection. These techniques allow for more dynamic and adaptable state initialization, providing greater control over how and when your ViewModel’s state is set up. This approach ensures that your ViewModel can adapt to different environments or requirements, making your app more robust and easier to maintain.


If you have any comments or suggestions, please reach out to me on Twitter.

Photo by Rodion Kutsaiev on Unsplash