Home > Enterprise >  Rxjs Wait Operator
Rxjs Wait Operator

Time:10-14

I am struggling with rxjs operators. In fact, I have this example.

constructor() {}

  ngOnInit(): void {
    //this.demo();
  }

  demo = () => {
    const obs = interval(15000);

    obs.subscribe(this.handleMessage.bind(this));
  };
  handleMessage() {
    alert('Hello');
  }

I want to ignore all obs events when the user does not click on OK with alert. I was thinking to add a new observable in order to ignore obs events but it does not work

import { Component, OnInit } from '@angular/core';
import { BehaviorSubject, interval, Observable, Subscription } from 'rxjs';
import { filter, first, switchMap, take } from 'rxjs/operators';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  name = 'Angular';
  instance = new BehaviorSubject({ status: true });
  instanceObs$ = this.instance.asObservable();
  subscription = new Subscription();
  constructor() {}

  ngOnInit(): void {
    this.demo();
  }

  demo = () => {
    const obs$ = interval(5000);
    this.subscription = obs$
      .pipe(waitFor(this.instanceObs$.pipe(filter((r) => r.status))), take(1))
      .subscribe(this.handleMessage.bind(this));
  };
  handleMessage() {
    this.instance.next({ status: false });
    alert('Hello');
    this.instance.next({ status: true });
  }
}
export function waitFor<T>(signal: Observable<any>) {
  return (source: Observable<T>) =>
    signal.pipe(
      first(),
      switchMap((_) => source)
    );
}

Alert is an example I am using confirm devextrem for the real world scenario with async operator

async handleUpdateFromAnotherTab(message: IRocketBroadcastMessage) {
    this.instance.next({ status: false });
    let result = await confirm(
      'Data has been updated from another tab. Would you like to reload it?',
      'Warning'
    );
    if (result) {
      window.location.reload();
    }
    this.instance.next({ status: true });
  }
}

StackBlitz

CodePudding user response:

Try this.

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  name = 'Angular';
  alerted = false;
  subscription = new Subscription();

  constructor() {}

  ngOnInit(): void {
    this.demo();
  }

  demo = () => {
    const obs$ = interval(5000);
    this.subscription = obs$
      .pipe(filter( () => this.alerted === false))
      .subscribe(this.handleMessage());
  };

  handleMessage = () => {
    this.alerted = true;
    alert('Hello');
    this.alerted = false;
  }

}
  • Related