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

后端 未结 9 2197
庸人自扰
庸人自扰 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 14:55

    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
    });
    

提交回复
热议问题