Add RxJava Observer to the chain depending on the condition

I am writing an Android application. At some point, I need to check the result returned by the Retrofit method, and if it returns true, make another API request. Without Rx, the logic looks like this:

if(api.isVip()) {
   checkIfPendingCancellation();
} else {
   JoinVipActivity.start();
}

checkIfPendingCancellation() {
    if(api.pendingCancel()) {
        YourVipIsAboutToCancelActivity.start();
    } else {
        CancelVipActivity.start();
   } 
}

I know that you can wrap everything with Rx, but not quite exactly how to do it. Any suggestions?

+4
source share
1 answer

Assuming the API is not based on RxJava, you can do something like this:

Observable.just(1)
.map(v -> {
    if (api.isVip()) {
       if (api.pendingCancel()) {
           return 1;
       }
       return 2;
    }
    return 3;
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(v -> {
    if (v == 1) {
       YourVipIsAboutToCancelActivity.start();
    } else
    if (v == 2) {
       CancelVipActivity.start();
    } else {
       JoinVipActivity.start();
    }
});

(Note: Observable.just(1).map().subscribeOn()- my personal favorite way to speed up initial synchronous processing.)

, Retrofit RxJava Observables ( , ?), API Observable<Boolean>, flatMap:

api.isVip()
.flatMap(b -> {
    if (b) {
        return api.pendingCancel().map(c -> c ? 1 : 2);
    }
    return Observable.just(3);
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(v -> {
    if (v == 1) {
       YourVipIsAboutToCancelActivity.start();
    } else
    if (v == 2) {
       CancelVipActivity.start();
    } else {
       JoinVipActivity.start();
    }
});
+2

Source: https://habr.com/ru/post/1589275/


All Articles