I\'m working on networking for my app. So I decided to try out Square\'s Retrofit. I see that they support simple Callback
@GET("/user/{id}/
By the samples and conclusions in other answers, I think there is no big difference for simple one or two-steps tasks. However, Callback is simple and straightforward. RxJava is more complicated and too big for simple task. There is the third solution by: AbacusUtil. Let me implement above use cases with all three solutions: Callback, RxJava, CompletableFuture(AbacusUtil) with Retrolambda:
Fetch photo from network and save/display on device:
// By Callback
api.getUserPhoto(userId, new Callback() {
@Override
public void onResponse(Call call, Response response) {
save(response.body()); // or update view on UI thread.
}
@Override
public void onFailure(Call call, Throwable t) {
// show error message on UI or do something else.
}
});
// By RxJava
api.getUserPhoto2(userId) //
.observeOn(AndroidSchedulers.mainThread())
.subscribe(photo -> {
save(photo); // or update view on UI thread.
}, error -> {
// show error message on UI or do something else.
});
// By Thread pool executor and CompletableFuture.
TPExecutor.execute(() -> api.getUserPhoto(userId))
.thenRunOnUI((photo, error) -> {
if (error != null) {
// show error message on UI or do something else.
} else {
save(photo); // or update view on UI thread.
}
});
Load user details and photo in parallel
// By Callback
// ignored because it's little complicated
// By RxJava
Observable.zip(api.getUserDetails2(userId), api.getUserPhoto2(userId), (details, photo) -> Pair.of(details, photo))
.subscribe(p -> {
// Do your task.
});
// By Thread pool executor and CompletableFuture.
TPExecutor.execute(() -> api.getUserDetails(userId))
.runOnUIAfterBoth(TPExecutor.execute(() -> api.getUserPhoto(userId)), p -> {
// Do your task
});