"Filter" with combineLatest

1,101 views
Skip to first unread message

Dave Jensen

unread,
Oct 8, 2015, 1:59:40 AM10/8/15
to RxJava
I have a situation where I want to use combineLatest (actually withLatestFrom) and filter some of the combinations.

Let's say I have Observable<Temperature> and Observable<Boolean>. I would like to use something like combineLatest to only emit Temperature when the Boolean is true. I'd rather not have to use an intermediary object like Pair<Temperature, Boolean>.

i.e., is there a better way than this:

Observable<Temperature> observableTemperature = getTemp();
Observable<Boolean> observableBoolean = getTempPrefs();

Observable
  .combineLatest(observableTemperature, observableBoolean, (Func2) (thing, aBoolean) -> {
      return new Pair<Thing, Boolean>(thing, aBoolean);
  })
  .filter((Func1) (thingBooleanPair) -> {
      return thingBooleanPair.second;
  })
  .map((Func1) (thingBooleanPair) -> {
      return thingBooleanPair.first;
  });






Dave Jensen

unread,
Oct 8, 2015, 2:07:12 AM10/8/15
to RxJava
Correction Thing should be Temperature.

I'm also not too happy with this solution either. I just don't like having to use the intermediate Pair object to do this task.

Observable
  .combineLatest(observableTemperature, observableBoolean, (Func2) (temperature, aBoolean) -> {
      return new Pair<Temperature, Boolean>(temperature, aBoolean);
  })
  .flatMap((Func1) (temperatureBooleanPair) -> {
    if (temperatureBooleanPair.second)
      return Observable.just(temperatureBooleanPair.first);
    else
      return Observable.just(temperatureBooleanPair.first).skip(1);
  });

Dávid Karnok

unread,
Oct 8, 2015, 3:22:24 AM10/8/15
to RxJava
Unfortunately, one can't filter and map with a single function (without out parameters like in C#) so all solution would wrap and allocate. However, the withLatestFrom is so simple you could just create a version of it with filter+map and lift it into your stream: https://gist.github.com/akarnokd/3b97ce85079f431addc2
Reply all
Reply to author
Forward
0 new messages