0

I have this seemingly easy use case where in a screen I display data based on sort, and pageIndex, both of which change via UI. So solution is easy

Observable
    .combineLatest(sortObservable, pageIndexObservable, Pair::of)
    .switchMap(tuple -> getData(tuple.sort, tuple.pageIndex))

However when sort changes, pageIndex should reset to 0.

If I do

Observable
    .combineLatest(
         sortObservable.doOnNext(__ -> pageIndexObservable.onNext(0),
         pageIndexObservable, Pair::of)
    .switchMap(tuple -> getData(tuple.sort, tuple.pageIndex))

Then it emits (last sort, 0) and then right away (new sort, 0), id obviously only want to get that (new sort, 0), or somehow ignore that (last sort, 0), i.e. conditionally block pageIndexObservable from emitting.

I dont want to use withLatestFrom because I want pageIndexObservable emits to trigger getData

Thanks

urSus
  • 12,492
  • 12
  • 69
  • 89
  • Maybe have one `Observable` upfront instead of two separate `Observable`s. The gui thread can then send in a `Pair` which may indicate both sorting and page 0. – akarnokd Jan 29 '18 at 18:48
  • But those values come from different "sources" (views; toggle and bottom of scrolling list). Do you say I should keep the last values manually in fields and construct the pair outside of rx? – urSus Jan 29 '18 at 18:54
  • 1
    Yes, have a field with the last `Pair` and whenever the sources signal, construct a new `Pair` based on the current one, save it and send it through the `switchMap`. For example, a `BehaviorSubject` could be used as the storage and its `getValue` to retrieve the current state. – akarnokd Jan 29 '18 at 19:16

1 Answers1

0

You can use a BehaviorSubject<Pair> and two update rules:

BehaviorSubject<Pair> query = BehaviorSubject.createDefault(Pair.of(0, 0));

query
.switchMap(tuple -> getData(tuple.sort, tuple.pageIndex))
.subscribe(/* ... */);

// ---------------------------------------

void changeSorting(int sort) {
    Pair current = query.getValue();
    query.onNext(Pair.of(sort, 0));
}

void nextPage() {
    Pair current = query.getValue();
    query.onNext(Pair.of(current.sort, current.pageIndex + 1));
}
akarnokd
  • 69,132
  • 14
  • 157
  • 192