Entering ViewModel

ViewModel is the Jetpack component that we will need to extend in order to host the orchestration of several other components. The orchestration of the other components will result in fulfilling our business goals.

Usually in a ViewModel we will need to make some API calls or Database operations and accordingly display our updated information in the UI consumer of our ViewModel.

The components that we will showcase and are currently using in our example project, are UseCases aka Interactors.

We prefer to “inject” those usecases into the constructor of our ViewModel. By doing this, we gain in testability.

Constructor injection

With Koin

A ViewModel can have its dependencies injected on its constructor pretty easily if we are making use of Koin.

We declare a new Koin module like the following:

We use factory in order to always get a new instance injected in our ViewModel (depending on the needs of our app and the work done by our usecase, it might be suitable to declare it as a singleton). The rest of the dependencies of our UseCase are fetched from the rest of the graph (we will analyze that in a future article).

With Dagger

In order to inject dependencies through constructor when using Dagger, we need to create a ViewModelFactory and bind our ViewModels by their class name to the Dagger graph.

A quick implementation of that injection is the following: