Getting an Observable that emits two types

280 views Asked by At

So I currently have one Observable, which returns the user:

 public Observable<Account> getLoggedUserInfo() {


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

    } catch (NullPointerException e) {

        return Observable.empty();

    }


}

And I have an Observable, which returns a school, based on the id, which looks like this:

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

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

}

Now I want to represent the school on my view, but in order to do that I need to create an Observable which would give me the account that I started with ( the Observable getLoggedUserInfo) and the school that happened after it, so i'd be ending up with something like

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

}

So how do I obtain this Observable, with the observables I currently have, is it even possible ? I'm still fairly new to Rx and the big part that confuses me is the syntax, thanks in advance !

1

There are 1 answers

0
Asti On

Use a tuple or an intermediary class.

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

I recommend you use proper tuples, but it can be as simple as:

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; 
  } 
}