The Repository Class

classes are responsible for handling data operations. They provide a clean API to the rest of the app for app data. They know where to get the data from and what API calls to make when data is updated. They are mediators between different data sources (persistent model, web service, cache, etc.).

Unlike the Room, LiveData or ViewModels, the repository class you'll create does not extend or implement an Architecture Components library. It is simply one way of organizing data in your app.

Nothing besides the repository class will communicate directly with the database or network packages, and the data and network packages will not communicate with classes outside of their respective packages. Thus the repository will be the UI's API for getting data to display on the screens.

Setting Up The Repository

The repository is a singleton class.

The most testable way to design the code is to pass an instance of your depency into the ViewModel - this would allow you to easily mock the repository when you're testing the view model.

The constructor that is automatically called by ViewModelProvider is the default one - it takes no arguments. If you want to create a different constructor for a view model, you'll need to make a view model provider factory.

public class DetailViewModelFactory extends ViewModelProvider.NewInstanceFactory {

   private final SunshineRepository mRepository;

   public DetailViewModelFactory(SunshineRepository repository) {
       this.mRepository = repository;
   }

   @Override
   public <T extends ViewModel> T create(Class<T> modelClass) {
       //noinspection unchecked
       return (T) new DetailActivityViewModel(mRepository);
   }
}

To Create a view model provider factory:

  • Extend ViewModelProvider.NewInstanceFactory
  • Add the custom parameters, ie: the Repo
  • Override the onCreate() method which calls the custom view model constructor

Then use the factory,

// Get the ViewModel from the factory
DetailViewModelFactory factory = new DetailViewModelFactory(repository);

mViewModel = ViewModelProviders.of(this, factory).get(DetailActivityViewModel.class);

results matching ""

    No results matching ""