scheduler_showcase.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. import { asyncScheduler, interval, Observable } from 'rxjs';
  2. import { delay, filter, map, observeOn, tap } from 'rxjs/operators';
  3. // Create an observable that emits a number every second
  4. const source$: Observable<number> = interval(1000);
  5. // Create an observable that emits a random boolean value every second
  6. const trigger$: Observable<boolean> = interval(1000).pipe(
  7. // tap(() => console.log('Trigger emitted')),
  8. map(() => Math.random() < 0.5),
  9. tap(triggered => {
  10. console.log('Scheduler triggered by:', triggered);
  11. })
  12. );
  13. let triggerSubscription = trigger$.subscribe((val) => {
  14. if (val) { // if it's true
  15. console.log(`Starting scheduler... ${val}`);
  16. source$.pipe(
  17. observeOn(asyncScheduler)
  18. ).subscribe(() => console.log('Scheduler completed. Starting source...'));
  19. // Pause trigger emissions while waiting for the scheduler to complete
  20. triggerSubscription.unsubscribe();
  21. setTimeout(() => {
  22. console.log('Resuming trigger emissions...');
  23. triggerSubscription = trigger$.subscribe();
  24. }, 5000);
  25. }
  26. });
  27. source$.subscribe(e=>{
  28. console.log(e)
  29. })
  30. // Not applicable to the our solution. There's no way to dynamically activate scheduler or assign it to existing observable emission.
  31. // Going back to test3 asyncScheduler example, it can only delay the amount of time (prefined), and then subscribe. There 's no way
  32. // to delay an existing observable unless we pipe it, which is not something we want to do since we want to save space in the first place.
  33. // Piping means creating another observable