MVP-3: Access (and cache) the data provided by Models via app-scoped dedicated components.


Description

When developing an Android app, a common issue which might emerge is related to restoring the state of Views. This issue can be solved by adapting slightly the architecture of apps. Specifically a data manager component (e.g., a data store or Jetpack Repository) can be introduced. This component is responsible for data related tasks such as fetching data from the network, caching results or returning already cached data. By scoping such component at the app level and not at the one of single Activities, issues relative to restoring View states, e.g., in the occurrence of a screen orientation change, are solved through an architecturally maintainable solution.

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.

Login Injection

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, which it will listen to with using the onSuccess or onError function.

The repository contains a EmployeeService which makes API requests and a EmployeeCache.

https://gist.github.com/Geertdepont/6ecccdffb113b1b2e581775384f4bc6c

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 is used during the API request.

This results in a faster response. If this data was stored in the MainActivity and this activity would be destroyed, the data would be lost. To retrieve the data again a new request would have to be performed, which results in a bad user experience.

Check out the Github page to view the complete repository.

<a href=”https://github.com/Geertdepont/bachelor_thesis/tree/master/Bossapplication” target=”_blank”target=”_blank”></a>