RxJava对象转换

时间:2015-10-09 05:55:40

标签: java retrofit rx-java

这就是我想要做的事情:

我需要使用RxJava和Retrofit链接两个网络调用。

  1. 第一个电话会检索Observable<User>

  2. 第二次调用会检索其他信息Observable<UserAdditionalInfo>,这些信息需要附加到之前检索到的Observable<User>

  3. 然后,检索附加了附加信息的Observable<User>

  4. 我已尝试使用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));
    

1 个答案:

答案 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>