【问题标题】:Getting an Observable that emits two types获取一个发出两种类型的 Observable
【发布时间】:2017-01-01 00:06:21
【问题描述】:

所以我目前有一个Observable,它返回用户:

 public Observable<Account> getLoggedUserInfo() {


    try {
        return accountService.me(preferencesHelper.getToken()).concatMap(remoteAccount -> {
            return localDatabase.addAccount(remoteAccount);
        });

    } catch (NullPointerException e) {

        return Observable.empty();

    }


}

我有一个Observable,它根据 id 返回学校,如下所示:

  public Observable<School> getSchoolById(@NonNull final String id){

    return schoolService.getSchool(id).concatMap(remoteSchool->localDatabase.addSchool(remoteSchool));

}

现在我想在我的观点上代表学校,但为了做到这一点,我需要创建一个Observable,它会给我我开始使用的帐户(ObservablegetLoggedUserInfo)和学校那是在它之后发生的,所以我最终会得到类似

的东西
Observable<Account, School>{
//Do something with the account and school

}

那么我如何获得这个Observable,使用我目前拥有的可观察对象,它甚至可能吗? 我对 Rx 还是很陌生,让我感到困惑的是语法,在此先感谢!

【问题讨论】:

    标签: java android system.reactive reactive


    【解决方案1】:

    使用元组或中间类。

    public Observable<Tuple<<Account, School>> doSomething() {
       return getLoggedUserInfo().zip(getSchoolById("id"), (f, s) -> new Tuple(x, y));
    }
    

    我建议您使用正确的元组,但它可以很简单:

    public class Tuple<X, Y> { 
      public final X x; 
      public final Y y; 
      public Tuple(X x, Y y) { 
        this.x = x; 
        this.y = y; 
      } 
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 2013-05-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      相关资源
      最近更新 更多