java - 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.
解决方案
我建议将 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 */);
推荐阅读
- knockout.js - Knockout/Select2 remove selected options from dropdown options. Without passing down root model
- iis - 管道中缺少使用 RM 任务的 IIS Web 部署
- javascript - JavaScript 中的类属性
- java - 如何为 travis CI 指定 JDK 的版本
- automation - 从 Maximo 中的自动化脚本保存工作订单
- r - R - How to remove NAs when using ASSIGN with a FOR LOOP?
- python - Deleting channels, and only running code if a USER, not BOT reacts to a message
- c# - 提高绘制图像的性能,SIMD 可能是一个解决方案吗?
- sql - SQL - 查找状态更改(降级)和总实例数的最近日期
- c# - IIS 不会绑定证书