Search code examples
angularrxjs5

Rxjs, how to pause the stream and wait the user click


I have a stream who starts by an http request :

this.myService.getData()

After getting the data, I have a filter operator :

.filter(() => boolean)

In this filter I want to wait an answer from the user, like 'Do you want to continue ?' Then the user click on 'Yes' or 'No'.

If the user clicks on 'Yes' then the stream continue with data.

If the user clicks on 'No' then the filter does its job.

It works fine with the confirm() native function but I need a custom modal, I won't use package like @angular/material, because I would like to know how to do this from scratch.

I'm pretty sure that a good way is to use Promise stuffs in the stream.

Do you how to resolve it ?


Solution

  • Initialize a subject on your component and call the .next() function when the user clicks any button on the modal. Then pipe the getData Observable into flatMap and evaluate the next value emitted by the subject.

    public onModalButtonClick = new Subject<boolean>();
    public openModal(): void {
        this.showModal = true;
        this.http.get('https://jsonplaceholder.typicode.com/todos/1').pipe(
          flatMap(data => {
            return this.onModalButtonClick.pipe(
              take(1),
              flatMap((bool) => bool? of(data) : throwError("abort button clicked"))
            )
          }),
          finalize(() => this.showModal = false)
        ).subscribe(data => {
            console.log(data);
          }, error => {
            console.log(error);
          });
      }
    

    I made a simple blitzstack. You may need to adjust this for your needs: https://stackblitz.com/edit/angular-zkx7kf?file=src%2Fapp%2Fhello.component.ts