Android. Less Dagger boilerplate code for ViewModel creation

Alex Misiulia
AndroidPub
Published in
2 min readMay 21, 2019
Photo by Ricardo Cruz on Unsplash

Dagger architecture component traditional approach

Usually, I face this approach for creating ViewModel with architecture components in Android. Typically we need 3 classes for creating ViewModel. For this sample, I place all dagger related classes in one file.

Notice that we mark ViewModelFactory as @Singleton because it provides the map with all ViewModels. That’s not very good, but not critical because we use Provider wrapper which will create aViewModel object only when we call get() method.

Every time we add the new ViewModel to the project we need to add it to the ViewModelModule class. That’s not critical too, but not very good.

Dagger architecture components approach without boilerplate code

What if we can create the ViewModelFactory which can create a specific instance of the ViewModel? And of course, we don’t want to collect some MutableMap of all ViewModel in the app.

Here is the concise implementation of the ViewModelFactory:

We pass the generic param of the ViewModel that we want to create inside the Factory. We don’t need a MutableMap, we just pass the provider for the ViewModel which will be used at the current screen.

You can check logs during the screen rotation and verify that the ViewModel persists across orientation changes.

Disadvantages of a new approach:

  • ViewModelFactory will be not a singleton. Every time you inject it new instance will be created.

Advantages:

  • You don’t need to create three files. You just need a few lines of code.
  • Don’t need to add a Provider method when adding new ViewModel.
  • If you forget to add @Inject constructor annotation or @Provides method dagger will fail at compile time.

Link to the source code of the app. The branch dagger_old_approach shows how the code looks like before and the branch dagger_new_approach shows new approach.

This post is created by using these links, many thanks to authors:

My name is Alex Misiulia and I am passioned about tech (especially Android). Feel free to reach me on Twitter and LinkedIn and ask questions about android development.

--

--