- Notifications
You must be signed in to change notification settings - Fork 6.3k
Open
Labels
Milestone
Description
Guide on managing callback complexity
Could you please send me some code example for structuring a chain of callbacks?
For example using includes to join data or ParseRelation to load associations.
Also, move the callbacks into an object with each request in a method and then use an interface to send out the requests (pseudo-code):
class ObjectFetcher { public interface FetcherCallbacks { void onFirstDataLoaded(Model impartialData); void onAllDataLoaded(Model data); } FetcherCallbacks callback; int requestsLoadedFlag = 0; public ObjectFetcher(FetcherCallbacks callback) { this.callback = callback; } public void loadAll() { sendFirstRequest(); sendSecondRequest(); sendThirdRequest(); } private void sendFirstRequest() { object.findAllInBackground(new Parse { void onDone(Error error) { requestsLoadedFlag +=1; // STORE DATA IN MEMBER VARIABLE HERE callback.onFirstDataLoaded(data); sendFinalDataWhenReady(); } }); } private void sendSecondRequest() { object.findAllInBackground(new Parse { void onDone(Error error) { requestsLoadedFlag +=1; // STORE DATA IN MEMBER VARIABLE HERE sendFinalDataWhenReady(); } }); } private void sendThirdRequest { object.findAllInBackground(new Parse { void onDone(Error error) { requestsLoadedFlag +=1; // STORE DATA IN MEMBER VARIABLE HERE sendFinalDataWhenReady(); } } } private void sendFinalDataWhenReady() { if (requestsLoadedFlag == 3) { callback.onAllDataLoaded(data1, data2, data3); } } }
and then use with something like:
ObjectFetcher fetcher = new ObjectFetcher(new FetcherCallbacks() { void onFirstDataLoaded { // … callback fired here } void onAllDataLoaded { // … callback fired here } })
Note that this is psuedocode but hope it gives you an idea of how to manage things using objects and interface callbacks.