buffer_showcase.ts 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. import { interval } from 'rxjs';
  2. import { buffer, filter, map, pairwise, tap } from 'rxjs/operators';
  3. // // Create an observable that emits a number every second
  4. // const source$ = interval(1000);
  5. // // Create an observable that emits a random boolean value every 3 seconds
  6. const trigger$ = interval(1000).pipe(
  7. map(() => Math.random() < 0.5),
  8. tap(triggered => {
  9. if (triggered) {
  10. console.log('Buffering triggered by:', triggered);
  11. } else {
  12. console.log('Buffering not triggered by:', triggered);
  13. }
  14. })
  15. );
  16. // // Buffer the values emitted by source$ between two true values emitted by trigger$
  17. // source$.pipe(
  18. // buffer(trigger$.pipe(
  19. // pairwise(),
  20. // filter(([prev, curr]) => prev === false && curr === true),
  21. // map(([_, curr]) => curr)
  22. // ))
  23. // ).subscribe(bufferedValues => {
  24. // console.log('Buffered values:', bufferedValues);
  25. // });
  26. const intervalEvents = interval(1000);
  27. const buffered = intervalEvents.pipe(buffer(trigger$.pipe(filter(value => !value))));
  28. // const buffered = intervalEvents.pipe(buffer(trigger$.pipe(map(val => !val))));
  29. buffered.subscribe(x => console.log(x));