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}/
The Observable stuff is already done in Retrofit, so the code could be this:
api.getUserPhoto(photoId)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Photo>() {
@Override
public void call(Photo photo) {
//save photo?
}
});
We usually go with the following logic:
In the case of getUserPhoto() the advantages for RxJava aren't great. But let's take another example when you'll get all the photos for a user, but only when the image is PNG, and you don't have access to the JSON to do the filtering on the serverside.
api.getUserPhotos(userId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.flatMap(new Func1<List<Photo>, Observable<Photo>>() {
@Override
public Observable<Photo> call(List<Photo> photos) {
return Observable.from(photos);
}
})
.filter(new Func1<Photo, Boolean>() {
@Override
public Boolean call(Photo photo) {
return photo.isPNG();
}
})
.subscribe(
new Action1<Photo>() {
@Override
public void call(Photo photo) {
// on main thread; callback for each photo, add them to a list or something.
list.add(photo)
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
// on main thread; something went wrong
System.out.println("Error! " + throwable);
}
},
new Action0() {
@Override
public void call() {
// on main thread; all photo's loaded, time to show the list or something.
}
});
Now the JSON returns a list of Photo's. We'll flatMap them to individual items. By doing so, we'll be able to use the filter method to ignore photos which are not PNG. After that, we'll subscribe, and get a callback for each individual photo, an errorHandler, and a callback when all rows have been completed.
TLDR Point here being; the callback only returns you a callback for succes and failure; the RxJava Observable allows you to do map, reduce, filter and many more stuff.