MVVM-10: Networking or data access functionalities should be performed exclusively by Models


Description

Performing data functionalities by models, results into smaller ViewModels/Views. It also makes testing the whole architecture easier. Since each component can be tested separately. Instead of asserting that a View needs to behave after a certain retrieval from the model, the model now can be tested independently.

Example

We created a simple MVVM-Example.

We use for this example Rxjava in combination with retrofit. Sometimes it is necessary to have nested callbacks. Like in this example, where we want to find the contributors of our repository. We need to know which repositories there are before we can look up, the contributors of the repository.

Our methods getRepositories() and getContributors(String repo), both return observable Values. Which means that this values can be viewed by an Observer, which we need to Implement.

We then create a Retrofit class, which returns a Retrofit instance, which will perform our API requests to “”https://api.github.com/””

In our repository, we will return our A Single object. Which either emits one value, or an error message.

This getContributorList() performs for each Repository a new request. Repo -> myApi.getContributors(repo.getName()) It then sorts all the results and puts them in a List.

RxJava depicted

The repository is the only module which performs Networking functionalities.

Check this page to view the complete repository.