GENERIC-8: Locally cache data for supporting offline-first experience.


Description

Using a cache to store data, enhances the user’s experience. Activities are destroyed constantly. Retrieving data from the server whenever an activity is destroyed, is a waste of mobile data and a bad user experience. A synchronization of a local database and the webservice can solve this problem. Whenever the local database is empty, or the data is not valid, retrieve data from the web server.

Example

We created a simple application which retrieves employees from this url: http://dummy.restapiexample.com/api/v1/

If the employees were already retrieved within 5000 milliseconds, the repository returns the cache instead of making a new API request.

Rxjava packages

In the mainActivity when the button is clicked, the function showEmployees is called from the MainPresenter.

The MainPresenter then asks the repository to show the users with the getList(this) function, which it will listen to with using the onSuccess or onError function.

The repository contains a EmployeeService and a EmployeeCache. The EmployeeService makes API requests and in the EmployeeCache the Employee is saved from the last request.

When the getList() function from the Repository is called. It checks if the cache is still valid. That is if the data was recently updated and not null.

If not, then a new listener is created which talks to the MainPresenter which in the getList() function has the name callback. Whenever the new the service request has an error the onError method from the listener is called, and in return calls the onError method from the MainPresenter. Whenever the new the service request is successful the onSuccess method from the listener is called, and in return calls the onSuccess method from the MainPresenter. Using a cache results in a faster response.

When using online services, do not forget to add the in the AndroidManifest.xml

Check out the Github page to view the complete repository.