这就是我想要做的事情:
我需要使用RxJava和Retrofit链接两个网络调用。
第一个电话会检索Observable<User>
。
第二次调用会检索其他信息Observable<UserAdditionalInfo>
,这些信息需要附加到之前检索到的Observable<User>
。
然后,检索附加了附加信息的Observable<User>
。
我已尝试使用flatMap
运营商:
Observable<User> userObservable = new RestClient().getUserById(1234);
userObservable.flatMap(new Func1<User, Observable<?>>() {
@Override
public Observable<?> call(User user) {
OtherRestClient otherRestClient = new OtherRestClient();
// Second network call. It retrieves an Observable<UserAdditionalInfo>
otherRestClient.getUserAdditionalInfo(user.getUserCode());
// I think, here should be the code that attaches the additional info
// to the `user` parameter of the call method and return an Observable<User>
return null;
}
}).subscribe(o -> System.out.println(o));
答案 0 :(得分:3)
这是你需要的吗?
Observable<User> userObservable = new RestClient().getUserById(1234);
userObservable.flatMap(new Func1<User, Observable<User>>() {
@Override
public Observable<User> call(final User user) {
OtherRestClient otherRestClient = new OtherRestClient();
// Second network call. It retrieves an Observable<UserAdditionalInfo>
Observable<UserAdditionalInfo> additionalObservable = otherRestClient.getUserAdditionalInfo(user.getUserCode());
return additionalObservable.map(new Func1<UserAdditionalInfo, User>() {
@Override
public User call(final UserAdditionalInfo uai) {
user.setXXX(uai.getXXX());
// ... any additional calls
return user;
}
});
}
}).subscribe(o -> System.out.println(o));
userObservable.flatMap(...)
语句的返回类型,如果我们在结尾处省略.subscribe(...)
部分,则为Observable<User>
。