Skip to content

Instantly share code, notes, and snippets.

@NinoDLC
Created August 23, 2021 20:48
Show Gist options
  • Save NinoDLC/592c4f1c4548124bfeaf8542d0008096 to your computer and use it in GitHub Desktop.
Save NinoDLC/592c4f1c4548124bfeaf8542d0008096 to your computer and use it in GitHub Desktop.
Caching data in RAM
import android.util.LruCache;
import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import fr.delcey.go4lunch.data.restaurant_details.pojo.RestaurantDetailsResponse;
import fr.delcey.go4lunch.data.restaurant_details.pojo.RestaurantDetailsResponseWrapper;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* This Repository is very important to avoid giving $$$ to Google because we made too many requests to the Places (Detail) API.
* It caches the RestaurantDetails in a LruCache to avoid querying too much data online.
*/
public class RestaurantDetailsRepository {
@NonNull
private final RestaurantDetailsApi restaurantDetailsApi;
private final LruCache<String, RestaurantDetailsResponse> cache = new LruCache<>(2_000);
public RestaurantDetailsRepository(@NonNull RestaurantDetailsApi restaurantDetailsApi) {
this.restaurantDetailsApi = restaurantDetailsApi;
}
@MainThread
@NonNull
public LiveData<RestaurantDetailsResponse> getRestaurantDetailsLiveData(@NonNull String placeId) {
MutableLiveData<RestaurantDetailsResponse> restaurantDetailsResponseMutableLiveData = new MutableLiveData<>();
// 1. We search in our cache with the placeId
RestaurantDetailsResponse existing = cache.get(placeId);
if (existing != null) {
// 2a. We found a similar query already existing, great ! No need to waste resources with an API call on Google's servers
restaurantDetailsResponseMutableLiveData.setValue(existing);
} else {
// 2b. Nothing similar in cache, query Google !
restaurantDetailsApi.getRestaurantDetails(placeId).enqueue(new Callback<RestaurantDetailsResponseWrapper>() {
@Override
public void onResponse(
@NonNull Call<RestaurantDetailsResponseWrapper> call,
@NonNull Response<RestaurantDetailsResponseWrapper> response
) {
RestaurantDetailsResponseWrapper body = response.body();
if (body != null) {
// 3. Save the result for next time...
cache.put(placeId, body.getRestaurantDetailsResponse());
restaurantDetailsResponseMutableLiveData.setValue(body.getRestaurantDetailsResponse());
}
}
@Override
public void onFailure(@NonNull Call<RestaurantDetailsResponseWrapper> call, @NonNull Throwable t) {
t.printStackTrace();
}
});
}
return restaurantDetailsResponseMutableLiveData;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment