Home > Back-end >  rxjs countdown that triggers method
rxjs countdown that triggers method

Time:10-24

I am trying to make a 5 mins countdown that triggers a service method and reloads the 5 mins countdown (basically I am trying to reload some data every 5 mins)

  constructor(
    private reloadDataService: ReloadDataService,
    private userService: UserService
    ) {
      this.timer$ = timer(0, 1000).pipe(
        scan(acc => --acc, 300),
        takeWhile(x => x >= 0),
      );
    }

realod method is trigger by a button or every 5 mins

  reload() {
    this.lastRefresh = new Date();
    this.reloadDataService.reload()
  }

  ngOnInit() {
    this.getUserDetails();
  }

I have tried with

this.timer$ = timer(0, 1000).pipe(
            switchMap(() => this.reload()),
            scan(acc => --acc, 300),
            takeWhile(x => x >= 0),
          );

but didn't work - how can I trigger the reload method every 5 mins?

CodePudding user response:

use the subscribe property of timer,

const source = timer(0, 300000);
source.subscribe((_) => this.reload());

CodePudding user response:

Try below code. It will setup the the interval method and when subscribing to refreshInterval$ you can call reload method or any operation that you want to repeat.

const refreshInterval$: Observable<any> = timer(0, 300000)
  .pipe(
    // Boolean to kill the request if the user closes the component 
    takeWhile(() => this.killTrigger));
refreshInterval$.subscribe(() => {
    // Your code here 
});
  • Related