Advertisement
Guest User

Untitled

a guest
Jan 24th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. void getAllCountries(@NonNull final SelectCountryCallback callback, String username){
  2. // Attempt to get countries from local cache, if present
  3. if(dbData(callback)) return;
  4.  
  5. // Call API to get updated list of countries
  6. callToApi(callback,username);
  7. }
  8.  
  9. void callToApi(callback,username);
  10. {
  11. apiService.getCountries(username).enqueue(new Callback<CountriesResponse>() {
  12. @Override
  13. public void onResponse(final Call<CountriesResponse> call, final Response<CountriesResponse> response) {
  14. if (response.isSuccessful()){
  15. saveToDBAndCall(callback,response)
  16. } else {
  17. callback.onCountriesLoadFailed(new Throwable("An error occured while loading countries"));
  18. }
  19. }
  20.  
  21. @Override
  22. public void onFailure(Call<CountriesResponse> call, Throwable t) {
  23. callback.onCountriesLoadFailed(t);
  24. }
  25. });
  26. }
  27.  
  28. void dbData(callback){
  29. RealmResults<Country> countries = realm.where(Country.class).findAll();
  30. if (!countries.isEmpty()){
  31. callback.onCountriesLoaded(countries);
  32. return true;
  33. }
  34. return false;
  35. }
  36.  
  37. void saveToDBAndReturn(callback,response)
  38. {
  39. realm.executeTransaction(new Realm.Transaction() {
  40. @Override
  41. public void execute(Realm realm) {
  42. if (response.isSuccessful()){
  43. realm.copyToRealmOrUpdate(response.body().countries);
  44. callback.onCountriesLoaded(response.body().countries);
  45. }
  46. }
  47. });
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement