我正在使用Single.fromCallable()
进行网络调用,我想使用响应中的数据进行第二次调用。
如何链接这两个调用而不是嵌套它们?
private void queryForUser() {
Single.fromCallable(() -> remoteRepository.queryForUser()))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(response-> {
String username = response.getUsername();
//Perform second call
performSecondQuery(username);
}, err -> {
Log.e(TAG, "Failed to get user", err);
});
}
private void performSecondQuery(String username){
Single.fromCallable(() -> remoteRepository.performSecondQuery(username)))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(secondQueryResult -> {
Log.d(TAG, "performSecondQuery: " + secondQueryResult);
}, err -> {
Log.e(TAG, "Failed to perform second query", err);
});
}
我的Java lambda语法有些生疏,但使用flatMap()
应该会得到这样的结果:
private Single<Whatever> performSecondQuery(String username){
return Single.fromCallable(() -> remoteRepository.performSecondQuery(username)))
}
private void queryForUser() {
Single.fromCallable(() -> remoteRepository.queryForUser()))
.flatMap { response -> performSecondQuery(response.getUsername()) }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
// TODO something with the result
}, err -> {
Log.e(TAG, "Failed to get user", err);
});
}
(注意:我不知道第二个查询在做什么,所以我不知道Whatever
是什么——它将是remoteRepository.performSecondQuery()
的返回类型(