我很高兴在Android中使用RxJava和Retrofit。我已经成功编写了API调用并开发了界面。现在,我想以我可以发送两个请求的方式编写我的代码:第二个请求取决于第一个请求的值。如果有可能,有人可以指导我吗?如果是这样呢?任何代码段都会非常有用。
例如:以下是两个请求:
mCompositeDisposable.add(fcService.getStationList()
.subscribeOn(Schedulers.io()) // "work" on io thread
.observeOn(AndroidSchedulers.mainThread()) // "listen" on UIThread
.subscribe(this::handleResults, this::handleError)
);
mCompositeDisposable.add(fcService.getStationSensor("12345678")
.subscribeOn(Schedulers.io()) // "work" on io thread
.observeOn(AndroidSchedulers.mainThread()) // "listen" on UIThread
.subscribe(this::handleResults, this::handleError)
);
第二个请求可以使用第一个请求的响应中的值。是否可以以我只为其编写一次代码的方式合并这两个请求?
答案 0 :(得分:1)
使用flatMap运算符,您可以检查第一个调用的响应并选择要执行的下一个操作,这样您就可以构建一个可以订阅的新Observable(下一个“代码”是kotlin样式):
Single<StationSensor> newSingle =
fcService.getStationList().flatMap{ stationList ->
when(stationList){
"OK_value" -> fcService.getStationSensor(stationList)
else -> Single.error(RuntimeException("Error response"))
}
}