3

I am following the Android guide for using LiveData: https://developer.android.com/jetpack/docs/guide, I can make calls and get a list of objects back, but I don't understand how I could cache that list of objects, on the example I am not really sure how is defined the class UserCache and also, I don't know how can I add a caching time.

Could you point me how to do it, please?

This is the class:

    @Singleton
    public class UserRepository {

    private Webservice webservice;
    private UserCache userCache;

    public LiveData<User> getUser(String userId) {
    LiveData<User> cached = userCache.get(userId);
    if (cached != null) {
        return cached;
    }

    final MutableLiveData<User> data = new MutableLiveData<>();
    userCache.put(userId, data);
    // this is still suboptimal but better than before.
    // a complete implementation must also handle the error cases.
    webservice.getUser(userId).enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User> call, Response<User> response) {
            data.setValue(response.body());
        }
    });
    return data;
}

}

Thank you

lulu666
  • 99
  • 1
  • 12

1 Answers1

0

This should help with retrofit2

OkHttpClient okHttpClient = new OkHttpClient()
            .newBuilder()
            .cache(new Cache(WaterGate.getAppContext().getCacheDir(), 10 * 1024 *1024))
            .addInterceptor(chain -> {
                Request request = chain.request();
                if (NetworkUtil.isDeviceConnectedToInternet(WaterGate.getAppContext())) {
                    request = request.newBuilder().header("Cache-Control", "public, max-age=" + 60).build();
                } else {
                    request = request.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + 60 * 60 * 24 * 7).build();
                }
                return chain.proceed(request);
            })
            .build();
Retrofit.Builder()
      .client(okHttpClient)
      .build();
Mbuodile Obiosio
  • 1,463
  • 1
  • 15
  • 19
  • Thanks for your answer, how could I add that interceptor in the code that I just added? – lulu666 Jul 06 '18 at 08:10
  • ok, I think I know how to do it, but I dont really understand the meaning of max-age and max-stale – lulu666 Jul 06 '18 at 11:03
  • ok, I think I know how to do it. I guess max-age 60 means that all calls within 1 minute are going to bring the response from cache. What max-stale means? Is it the time that we are going to have it in cache? Why would you want it in cache for 1 week if you always refresh the cache every minute? To be able to work offline? – lulu666 Jul 06 '18 at 11:14
  • Yes. This is for offline support. – Mbuodile Obiosio Jul 06 '18 at 12:21