Keep list updated with Ionic 2 / Angular 2

守給你的承諾、 提交于 2019-12-06 19:23:25

You could solve this by using something like this:

// this can be a click-event, or anything else, in this case it'll just be a simple manualTrigger$.next();
let manualTrigger$ = new Rx.Subject();

// the timer will trigger immediately and then every 30seconds
let intervalTrigger$ = new Rx.Observable.timer(0, 30000);

// this is our actual combination "logic", a simple "switchMapTo"
// switchMap switches to a new subscription of our timer each time manualTrigger$ triggers and discards the old one
let resetIntervalWhenTriggeredManually$ = manualTrigger$
  .switchMapTo(intervalTrigger$);

// make sure to unsubscribe when the view is destroyed or just use the async-pipe in your template!
resetIntervalWhenTriggeredManually$
  .flatMap(makeRestCall); // here you insert your rest-call
  .subscribe(
      data => console.log("Data is:", data),
      error => console.error("Error: " + error)
  );

You can also checkout this jsbin here for a running example: http://jsbin.com/titujecuba/edit?js,console


The part where you want to automatically stop/continue the updates when the user leaves/enters the page, cannot be done with pure rxjs, you will have to keep a date somewhere of the last update and check is small periods:

// check every second
const thirtyMinutes: number = 1000 * 60 * 30;
let lastUpdated: number = -1;
let intervalTrigger$ = new Rx.Observable.timer(0, 1000);
let resetIntervalWhenTriggeredManually$ = manualTrigger$
  .do(() => lastUpdated = -1) // rest the last update to force an update
  .switchMapTo(intervalTrigger$)
  .filter(() => return +new Date() - lastUpdated >= thirtyMinutes) // only propagate dispatches if time elapsed is 30minutes
  .do(() => lastUpdate = +new Date());

resetIntervalWhenTriggeredManually$
  .flatMap(makeRestCall); // here you insert your rest-call
  .subscribe(
      data => console.log("Data is:", data),
      error => console.error("Error: " + error)
  );

And you will have to place this in a service, otherwise the state would be lost if the view is destroyed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!