codepath / codepath/android_guides

Managing Network Callbacks

Open
#50 0 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
No language data
Stars
28.3k
Forks
6.2k
PR merge metrics
No merged PRs in 30d

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):

``` java
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:

``` java
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.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.