vazha
vazha

Reputation: 58

Reset Rx Js fromEvent observable after subscribe

I have mousemove event:

 fromEvent(document, 'mousemove').pipe(
   filter(e => e.target !== this.formElement.nativeElement),
   filter(_ => this.form.valid),
   take(1),
   mergeMap((): any => this.confirm()),
   ).subscribe();


confirm() {
   this.snack.open('sure', 'yes').onAction()
   .subscribe(_ => {
      this.createNoteService.create();
    })
 } 

After confirming the snack button I want the mouse event to start working again.

Is it possible? Thanks!

Upvotes: 1

Views: 235

Answers (1)

BizzyBob
BizzyBob

Reputation: 14750

The reason this only works for you the first time, is because you have take(1) which ends the observable after one value is received.

Also, your confirm() method should return observable; don't subscribe inside the function; mergeMap will automatically subscribe / unsubscribe for you.

However, instead of mergeMap, you can use exhaustMap. This will only allow a single inner subscription at a time. It will ignore any incoming emissions until its current source completes:

fromEvent(document, 'mousemove').pipe(
  filter(e => e.target !== formElement.nativeElement),
  filter(_ => form.valid),
  exhaustMap(() => confirm()),
).subscribe();

function confirm() {
  return snack.open('sure', 'yes').onAction().pipe(
    tap(() => this.createNoteService.create())
  );
} 

Upvotes: 1

Related Questions