Many of us, when started learning how to use the new ViewModel class had a look at the GithubBrowserSample example on GitHub (this is a GitHub-ception!).

Maybe, the first class we looked in that bunch of useful code, is the so called GithubViewModelFactory class (here’s a link to the file in the repository).

This class is a perfect example of when Dagger 2 multibindings can be real lifesavers.

Before to dive into code, I should make a little premise.

For building custom ViewModel classes with argument-passing constructors (e.g. for passing custom data or @Inject annotated constructors), we must provide a class that extends ViewModelProvider.Factory , returning instances of our custom ViewModels into the create() method.

So, the first thing we can notice is the constructor of the class, that takes the not very beautiful to see Map<Class<? extends ViewModel>, Provider<ViewModel>> parameter. What is this monster?

Let’s read this huge parameter type with more attention: it is a map that has a Class that extends ViewModel as key, and a Provider of ViewModel (a Dagger 2-specific class that let us provide — and so instantiate — a dependency-injected class) as value.

Ok ok, but what can I do with this object?

Well, we just said that the create method of our custom ViewModelProvider.Factory expects an instance of the ViewModel as a return value. This method takes the type of the ViewModel that was requested from an Activity or Fragment as a parameter. Pairing this type (our Class object) to something that creates a ViewModel of the same type, we can, of course, instantiate and return that class to the system.

What is that “something” that can give us the ViewModel of a determinate type? The answer is the Provider value in the map that Dagger 2 injected us.

Let’s talk about Multibindings