Here are the libraries used. A complete app/build.gradle can be found here.

Dagger 2.11+ setup

For details on setting up Dagger for this project, please refer to https://github.com/jshvarts/DaggerAndroidMVVM or check out my article where I documented the new Dagger Android setup steps.

Data Model

Our UI buttons use separate repositories ( CommonGreetingRepository and LobbyGreetingRepository ), each producing a message that tells us what scope they belong to. Dependency injection and scoping is achieved through Dagger.

Note that both repositories expose their data as streams using RxJava 2 API. While overkill for a simple synchronous code like this, a typical Model is much more involved and utilizes asynchronous calls. So I definitely recommend using RxJava in those scenarios. If you are new to reactive programming, definitely read up on it — there are plenty of resources out there to get you started.

Use Cases aka Interactors

Our simple app handles two basic use cases depending on which button was clicked. In MVVM architecture View and ViewModel make up the Presentation Layer. Use Cases are the Domain Layer. And finally the Repositories are the Data Layer.

LoadCommonGreetingUseCase and LoadLobbyGreetingUseCase are injected into their corresponding scope by Dagger via constructor injection with @Inject

The Use Cases in this example are very basic but in a real world app they would contain more functionality possibly accomplished with help of other components injected into them. The use cases and their helpers could handle validation, reporting and other pre-processing tasks. Separate components handle specific thus achieving Single Responsibility principle of SOLID code design.

ViewModel

LobbyViewModel communicates with our View, LobbyActivity , by reacting to user interactions and exposing results via stream of events using RxJava. We will implement the LobbyViewModel using a combination of the new Android Architecture components ViewModel and LiveData. Let’s look at the code:

Our ViewModel interacts with Data Layer via Domain Layer (namely LoadCommonGreetingUseCase and LoadLobbyGreetingUseCase ). It turns Observable streams of data into Subscriptions (or Single streams into Disposable in our RxJava 2 scenario).

Because LobbyViewModel requires certain dependencies to be provided at construction type, we use custom ViewModelFactory to instantiate it. The factory itself gets injected into our View via Dagger.