Created
August 13, 2015 16:57
-
-
Save n8ebel/16212d1351f8623a1913 to your computer and use it in GitHub Desktop.
RxJava vs Callback
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
/* | |
* Standard way | |
*/ | |
// MarvelAndroid.getInstance().getCharacters(queryParams, | |
// new ResponseCallback<com.n8.marveldroid.EntityModelObjects.Character>() { | |
// @Override | |
// public void onRequestComplete(List<Character> responseEntities, Throwable error) { | |
// if (error != null) { | |
// mResultTextView.setText(error.getLocalizedMessage()); | |
// return; | |
// } | |
// | |
// String msg = ""; | |
// for (Character character : responseEntities) { | |
// msg += character.name + "\n"; | |
// } | |
// | |
// mResultTextView.setText(msg); | |
// | |
// MarvelAndroid.getInstance().getComicsForCharacterId(responseEntities.get(3).id, | |
// new ComicQueryParams(), new Callback<ServiceResponse<Comic>>() { | |
// @Override | |
// public void success(ServiceResponse<Comic> comicServiceResponse, | |
// Response response) { | |
// String imagePath = comicServiceResponse.data.results.get(0).images.get(0).path; | |
// imagePath += "/portrait_xlarge.jpg"; | |
// Log.d("foo", imagePath); | |
// Picasso.with(MainActivity.this).load(imagePath).into(mImageView); | |
// } | |
// | |
// @Override | |
// public void failure(RetrofitError error) { | |
// mResultTextView.setText(error.getLocalizedMessage()); | |
// Log.d("foo", error.getLocalizedMessage()); | |
// } | |
// }); | |
// } | |
// }); | |
/* | |
* RxJava | |
*/ | |
MarvelAndroid.getInstance().getCharacters(queryParams). | |
map(p1 -> new Pair<>(p1, p1.data.results.get(3).id)). | |
flatMap((p1) -> { | |
Observable<ServiceResponse<Character>> characterObservable = Observable.just(p1.first); | |
return MarvelAndroid.getInstance().getComicsForCharacterId(p1.second, new ComicQueryParams()). | |
zipWith(characterObservable, (comic, character) -> new Pair<>(character, comic)); | |
}). | |
observeOn(AndroidSchedulers.mainThread()). | |
subscribeOn(Schedulers.io()). | |
subscribe(pair -> { | |
String msg = ""; | |
for (Character character : pair.first.data.results) { | |
msg += character.name + "\n"; | |
} | |
mResultTextView.setText(msg); | |
String imagePath = pair.second.data.results.get(0).images.get(0).path; | |
imagePath += "/portrait_xlarge.jpg"; | |
Log.d("foo", imagePath); | |
Picasso.with(MainActivity.this).load(imagePath).into(mImageView); | |
}, | |
error -> mResultTextView.setText(error.getLocalizedMessage()), | |
()->{}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment