Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void getAllCountries(@NonNull final SelectCountryCallback callback, String username){
- // Attempt to get countries from local cache, if present
- if(dbData(callback)) return;
- // Call API to get updated list of countries
- callToApi(callback,username);
- }
- void callToApi(callback,username);
- {
- apiService.getCountries(username).enqueue(new Callback<CountriesResponse>() {
- @Override
- public void onResponse(final Call<CountriesResponse> call, final Response<CountriesResponse> response) {
- if (response.isSuccessful()){
- saveToDBAndCall(callback,response)
- } else {
- callback.onCountriesLoadFailed(new Throwable("An error occured while loading countries"));
- }
- }
- @Override
- public void onFailure(Call<CountriesResponse> call, Throwable t) {
- callback.onCountriesLoadFailed(t);
- }
- });
- }
- void dbData(callback){
- RealmResults<Country> countries = realm.where(Country.class).findAll();
- if (!countries.isEmpty()){
- callback.onCountriesLoaded(countries);
- return true;
- }
- return false;
- }
- void saveToDBAndReturn(callback,response)
- {
- realm.executeTransaction(new Realm.Transaction() {
- @Override
- public void execute(Realm realm) {
- if (response.isSuccessful()){
- realm.copyToRealmOrUpdate(response.body().countries);
- callback.onCountriesLoaded(response.body().countries);
- }
- }
- });
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement