首页 > 解决方案 > RxJava - making two calls where the first one is conditional

问题描述

I'm using RxJava 2 to do API's calls. I have to do a call to cancel the booking of a class.

But I must have to do or not one previous call to get missing information.

It's something like this:

if classId not exists
   get classId
   then unbook class
else
   unbook class

I don't want to repeat the unbook class code.

Here are the code simplified:

FitnessDataService service = RetrofitInstance.getRetrofitInstance().create(FitnessDataService.class);
        // if we don't have the aid of class (reserved), we get it from the reserved classes


        if (fitClass.getAid() == null) {
            service.getReservedClasses(FitHelper.clientId)
                    .flatMap(reservedClasses ->
                    {
                        // get the class ID from reserved classes
                         ...
                        return service.unbookClass(fitClass.getAid());
                    }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                                // success
                            }, err -> 
                                // error
        } else {
            service.unbookClass(fitClass.getAid())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(response -> {
                                // success
                            }, err -> 
                                // error
        }

As you can see, the service.unbookClass is repeated. How I can call always this service.unbookClass and only call the service.getReservedClasses if I don't have the class id (fitClass.getAid() == null) without repeating the code to the second call.

标签: javaandroidretrofitrx-java2

解决方案


我建议将 id 的实际来源分离到它自己单独的 observable 中。也许是这样的:

Observable<Long> idObservable;
if (fitClass.getAid() == null) {
    idObservable = service.getReservedClasses(FitHelper.clientId)
        .map({ reservedClasses ->
            /* Get the Id and do stuff with it */
            return fitClass.getAid();
        });
} else {
    idObservable = Observable.just(fitClass.getAid());
}

idObservable.flatMap({ aid -> service.unbookClass(aid) })
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(/* TODO */);

推荐阅读