Skip to content

Commit

Permalink
Cache the call to the cat API
Browse files Browse the repository at this point in the history
  • Loading branch information
AllanHasegawa committed Jul 30, 2017
1 parent 0a6c8b1 commit e39ee8c
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
6 changes: 4 additions & 2 deletions app/src/main/java/io/catter2/ListActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

import java.util.List;

import io.catter2.cat_api.CacheTheCatAPI;
import io.catter2.cat_api.FetchCatImagesUseCase;
import io.catter2.cat_api.RetrofitTheCatAPI;
import io.catter2.cat_api.TheCatAPI;
Expand Down Expand Up @@ -66,8 +67,9 @@ public void imageClicked(ImageView view, String url) {

FavoritesRepository favoritesRepository = new SharedPrefFavoritesRepository(this, userToken);
addFavoriteUseCase = new AddFavoriteUseCase(favoritesRepository);
TheCatAPI catAPI = new RetrofitTheCatAPI();
fetchCatImagesUseCase = new FetchCatImagesUseCase(catAPI);
TheCatAPI catAPIService = new RetrofitTheCatAPI();
TheCatAPI catAPICached = new CacheTheCatAPI(catAPIService);
fetchCatImagesUseCase = new FetchCatImagesUseCase(catAPICached);

fetchCatImagesUseCase.getImagesUrls(new FetchCatImagesUseCase.Callback() {
@Override
Expand Down
32 changes: 32 additions & 0 deletions app/src/main/java/io/catter2/cat_api/CacheTheCatAPI.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package io.catter2.cat_api;

import android.util.Log;

public class CacheTheCatAPI implements TheCatAPI {
private static String TAG = "CacheTheCatAPI";

private TheCatAPI service;
private CatImagesModel lastResponse;

public CacheTheCatAPI(TheCatAPI service) {
this.service = service;
}

@Override
public void getCatsWithHats(final Callback callback) {
if (lastResponse != null) {
Log.d(TAG, "Using cached response.");
callback.response(lastResponse);
} else {
Log.d(TAG, "Querying a new response.");
service.getCatsWithHats(new Callback() {
@Override
public void response(CatImagesModel response) {
Log.d(TAG, "Saving response to cache.");
lastResponse = response;
callback.response(response);
}
});
}
}
}

0 comments on commit e39ee8c

Please sign in to comment.