This code demonstrates 2 approaches to completing the same task, and performs the following actions:
- The task is to hit the Marvel rest endpoint, and return a list of characters.
- Take the 4th character in that list, fetch its comics, and then load the image for that comic.
- Once those requests are done, the image and list of character names are bound to the ui.
/*
* Standard way
*/
// marvelAndroid.getCharacters(queryParams, (responseEntities, error) -> {
// if (error != null) {
// mResultTextView.setText(error.getLocalizedMessage());
// return;
// }
//
// showCharacterData(responseEntities);
//
// marvelAndroid.getComicsForCharacterId(responseEntities.get(3).id,
// new ComicQueryParams(), new Callback<ServiceResponse<Comic>>() {
// @Override
// public void success(ServiceResponse<Comic> comicServiceResponse, Response response) {
// showComicImage(comicServiceResponse);
// Log.d("foo", "Standard way completed");
// }
//
// @Override
// public void failure(RetrofitError error) {
// mResultTextView.setText(error.getLocalizedMessage());
// Log.d("foo", error.getLocalizedMessage());
// }
// });
// });
/*
* RxJava
*/
marvelAndroid.getCharacters(queryParams).
map(p1 -> new Pair<>(p1, p1.data.results.get(3).id)).
flatMap((p1) -> marvelAndroid.getComicsForCharacterId(p1.second, new ComicQueryParams()).
zipWith(Observable.just(p1.first), (comic, character) -> new Pair<>(character, comic))
).
observeOn(AndroidSchedulers.mainThread()).
subscribeOn(Schedulers.io()).
subscribe(pair -> {
showCharacterData(pair.first.data.results);
showComicImage(pair.second);
},
error -> mResultTextView.setText(error.getLocalizedMessage()),
()->Log.d("foo", "RxJava way completed"));
}
What this doesn't illustrate well is the fact that any errors within the stream all get handled in
onError()
rather than crashing the app.In the standard approach, all of that error checking must be scattered throughout the code, or wrap the whole thing in a try/catch