Auto Caching

We’re gonna use Retrofit to make our http calls, gson for parsing and ObjectBox to cache the responses.

The idea is simple. Save every response annotated with @Cacheable directly into the database as a POJO, using Retrofit’s converter factory.

Converter

When building your Retrofit instance you have the option to add a converter factory, like so:

new Retrofit.Builder()

.baseUrl(URL)

.client(createClient())

.addConverterFactory(GsonConverterFactory.create())

.build();

We’ll use the gson converter provided by Retrofit and modify it slightly to include a listener in GsonResponseBodyConverter.class which handles the http response parsing.

The key line here is:

if (listener != null && isCacheable) listener.onCacheableResponse(clsType, response);

Whenever we get the response body we check if the @Cacheable annotation is present

and notify the listener with the response and response class type.