When should one use RxJava Observable and when simple Callback on Android?

后端 未结 9 2162
庸人自扰
庸人自扰 2020-11-29 14:05

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}/         


        
相关标签:
9条回答
  • 2020-11-29 15:03

    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?
                }
         });
    
    0 讨论(0)
  • 2020-11-29 15:03

    We usually go with the following logic:

    1. If it's a simple one-response call, then Callback or Future is better.
    2. If it's a call with multiple responses (stream), or when there are complex interaction between different calls (see @Niels' answer), then Observables are better.
    0 讨论(0)
  • 2020-11-29 15:06

    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.

    0 讨论(0)
提交回复
热议问题