How to make an http call every 2 minutes with RXJS?

…衆ロ難τιáo~ 提交于 2019-11-27 14:49:11

Since you are already using Observables, simply make full use of it :) Obersvable.interval() is your good friend here:

In your component, do this:

Observable
    .interval(2*60*1000)
    .timeInterval()
    .flatMap(() => this.notificationService.getNotifications(this.token))
    .subscribe(data => {
        console.log(data);
    });

Explanation:

  1. .interval() creates an observable that emits an event every 2 minutes.
  2. .timeInterval() convert an Observable that emits items into one that emits indications of the amount of time elapsed between those emissions.
  3. .flatMap() then wraps your each and every of service call, transform the results into an observable and return it. This ensure that the your service call at 0th, 2nd, 4th, 6th....minute is called synchronously. (think of there is a lot of .then()), i.e, service at 2nd minute will only be called on after the 0th minute's call, and 4th will only after 2nd, and so on.
  4. .subscribe() finally you can subscribe to the data

Update:

If you are using pipeable operators (rxjs5 and above), simply pipe the operators instead of chaining them:

interval(2 * 60 * 1000)
    .pipe(
        flatMap(() => this.notificationService.getNotifications(this.token))
    )
    .subscribe(data => console.log(data))

If you don't want to make an http call and simply want to do something after 2 minutes, then you can do something like below.

 Observable.interval(2*60*1000)
  .subscribe(() => {
    // do something.
    // or callSomeMethod();
  });

There is one more important thing you would like to do, You shoud destroy this observable once you leave your current page, because you don't want the extra computation going on behind the scene when these are not actually needed.

There are multiple options to unsubscribe from this observable.

  1. You should save the reference to the observable and unsubscribe from it in onDestroy method.

    this.observableRef = Observable.interval(60000)
    .subscribe(() => {
      // do something
     });
    
    // call this method in OnDestroy method of the page.
    this.observableRef.unsubscribe();
    
  2. OR use ngx-take-until-destroy

    Observable.interval(60000)
    .takeUntil(this.destroyed$)
    .subscribe(() => {
      //  do something
    });
    
import {Observable} from 'rxjs/Rx';

  Observable.interval(2 * 60 * 1000).subscribe(x => {
    callyourmethod();
  });

Update After comment

this.interval = setInterval(() => {
        this.yourservicecallmethod();
    }, 2 * 60 * 1000);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!