Sunday, 28 March 2021

How can I pause and resume an observable on document click?

I have an observable that emits certain values to the console on every second. I show an example below and a STACKBLITZ as well.

My dilemma is I need to able to pause it on the next document click and resume it (not restart it) it on the next one again. I was looking into switchMap and I couldn't figure out how to implement it.

export class AppComponent implements OnInit {
  title = "my-app";
  pageClickObservable: Observable<Event> = fromEvent(document, "click");

  ngOnInit(): void {
    new Observable();

    const watchForClick = () => {
      setTimeout(() => {
        console.log("A");
      }, 1000);
      setTimeout(() => {
        console.log("BB");
        console.log("10");
      }, 2000);
      setTimeout(() => {
        console.log("CCC");
      }, 3000);
      setTimeout(() => {
        console.log("DDDD");
        console.log("20");
      }, 4000);
      setTimeout(() => {
        console.log("EEEEE");
      }, 5000);
      setTimeout(() => {
        console.log("FFFFFF");
        console.log("30");
      }, 6000);
    };

    this.pageClickObservable.pipe().subscribe(() => {
      watchForClick();
    });
  }
}

Thanks in advance



from How can I pause and resume an observable on document click?

No comments:

Post a Comment