Last active
August 9, 2016 14:20
-
-
Save tonespy/c46d6d6729ab6618f906b050a2f22b1a to your computer and use it in GitHub Desktop.
Tail Recursion Retrofit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LgaHandler { | |
private static final String TAG = "Lgahandler"; | |
private static Context mContext; | |
private static Realm realm; | |
private static ClientBus clientBus; | |
private static int page = 1; | |
private static int perPage = 21; | |
public LgaHandler (Context realContext, Realm mRealm) { | |
if (mContext == null || realm == null) { | |
mContext = realContext; | |
realm = mRealm; | |
clientBus = ((FmnApplication) mContext).getRxBusSingleton(); | |
} | |
} | |
public void getLgas() { | |
if(!NetworkUtils.isConnected(mContext)){ | |
Log.e(TAG, "Stopping sync. Not connected to internet"); | |
if (clientBus.hasObservers()) { | |
clientBus.send(new MessageUpdate("State", 0, 0, 0, false, false)); | |
} | |
return; | |
} | |
new Thread(new Runnable() { | |
@Override | |
public void run() { | |
Log.e(TAG, "Getting Lgas From server"); | |
Call<LgaRespone> call = RestClient.get(mContext).getLgas(String.valueOf(page), String.valueOf(perPage)); | |
try { | |
final Response<LgaRespone> response = call.execute(); | |
if (response.isSuccess()) { | |
final LgaRespone lgaRespone = response.body(); | |
new Handler(Looper.getMainLooper()).post(new Runnable() { | |
@Override | |
public void run() { | |
int totalCount = lgaRespone.getResponse().getData().size(); | |
realm.beginTransaction(); | |
for (co.companyName.network.responses.Lgas.Datum lgaData : lgaRespone.getResponse().getData()) { | |
Lga lgaEntry = realm.where(Lga.class).equalTo("id", lgaData.getId()).findFirst(); | |
if (lgaEntry != null) { | |
// | |
} else { | |
Lga lga = new Lga(); | |
lga.setId(lgaData.getId()); | |
lga.setState_id(lgaData.getStateId()); | |
lga.setName(lgaData.getName()); | |
lga.setState(lgaData.getState()); | |
realm.copyToRealm(lga); | |
} | |
} | |
if (realm.isInTransaction()) { | |
realm.commitTransaction(); | |
} | |
page += 1; | |
if (lgaRespone.getResponse().getData().size() < 21 || lgaRespone.getResponse().getMeta().getPage() == lgaRespone.getResponse().getMeta().getPageCount()) { | |
if (clientBus.hasObservers()) { | |
clientBus.send(new MessageUpdate("Lga", 0, 0, 0, true, true)); | |
} | |
} else { | |
getLgas(); | |
} | |
} | |
}); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
new Handler(Looper.getMainLooper()).post(new Runnable() { | |
@Override | |
public void run() { | |
if (realm.isInTransaction()) { | |
realm.cancelTransaction(); | |
} | |
} | |
}); | |
} | |
} | |
}).start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment