skip to content

windowToggle

 

windowToggle operator lets you open and close a filtering window. Emissions between "on" and "off" events will be passed to the output stream. Read more about muting and spacing events on RxJS streams in my article "Pausable Observables in RxJS and other backpressure techniques"

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const { rxObserver } = require('api/v0.3');
const { timer, merge, Subject } = require('rxjs');
const { windowToggle, take, flatMap, mapTo } = require('rxjs/operators');


const source$ = timer(0, 10).pipe(take(10));

const windowOn$ = new Subject();
const windowOff$ = new Subject();

const result$ = source$.pipe(
  // filter values between on-off pairs
  windowToggle(
    windowOn$,
    ()=>windowOff$
  ),

  // flattern window values
  flatMap(v=>v)
);

// trigger ONs and OFFs
windowOn(15);
windowOff(35);

windowOn(75);
windowOff(85);


// subscriptions
source$.subscribe(rxObserver('source$'));
merge(
    windowOn$.pipe(mapTo('on')),
    windowOff$.pipe(mapTo('off'))
  )
  .subscribe(rxObserver('switch'));
result$.subscribe(rxObserver('result$'));



// helpers
function windowOn(delay){
  return setTimeout(()=>{
    windowOn$.next(void 0);
  }, delay);
}

function windowOff(delay){
  return setTimeout(()=>{
    windowOff$.next(void 0);
  }, delay);
}

0mssource$startcomplete00 11 22 33 44 55 66 77 88 99 switchstartonon offoff onon offoff result$startcomplete22 33 88