Skip to content

Instantly share code, notes, and snippets.

@n8ebel
Last active August 29, 2015 14:27
Show Gist options
  • Save n8ebel/13dbad32a3eec4315ab5 to your computer and use it in GitHub Desktop.
Save n8ebel/13dbad32a3eec4315ab5 to your computer and use it in GitHub Desktop.
RxJava vs Standard 2

This code demonstrates 2 approaches to completing the same task, and performs the following actions:

  1. The task is to hit the Marvel rest endpoint, and return a list of characters.
  2. Take the 4th character in that list, fetch its comics, and then load the image for that comic.
  3. 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"));

  }
@n8ebel
Copy link
Author

n8ebel commented Aug 13, 2015

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment