Search code examples
rxjsrx-java

Create observable that emits when a click occurs between two events


I'm looking to compose an observable that emits when a click occurs between a start and end event. A start event is always guaranteed to be followed by an end event before the next start event (and vice versa for end event). That is, the sequence is always guaranteed to look like this:

start -> end -> start -> end -> ...

I currently have it setup like this:

start$
  .pipe(
    switchMapTo(click$.pipe(take(1), takeUntil(end$)),
  )
  .subscribe(() => {
    console.log('click between start and end!');
  })

Is this the best way to set this up? Are there some alternative simple operators I can use to do the equivalent as the above without relying upon switchMapTo or switchMap? Thanks!


Solution

  • Consider using a single BehaviorSubject as a toggle, as demonstrated below:

    declare const toggle$: BehaviorSubject<boolean>;
    declare const click$: Observable<Event>;
    
    click$.pipe(
        withLatestFrom(toggle$),
        filter(([, predicate]) => predicate)
    );