Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2: How to debounce Observable.combineLatest calls?

Tags:

angular

rxjs

I'm having performance problems in my angular2 application because I have a big Observable.combineLatest() with many inputs which change quickly and I want to debounce the callback call:

myData$ = Observable.combineLatest(
  this.store.let(fromRoot.getFoo),
  this.store.let(fromRoot.getBar),
  this.store.let(fromRoot.getFoobar),
  this.store.let(fromRoot.getBarfoo),
  (foo, bar, foobar, barfoo) => {
     ...
  });

Calling debounce after the fact, e.g. Observable.combineLatest(...).debounceTime(300), is useless because the CPU intensive task is happening inside of the combineLatest callback which is still called often.

I guess I have to combine another Observable but I'm not sure how to do it, any ideas?

like image 892
arturh Avatar asked Dec 14 '16 21:12

arturh


2 Answers

The combineLatest method's project function is essentially a map operator. You could re-arrange things like this:

myData$ = Observable.combineLatest(
  this.store.let(fromRoot.getFoo),
  this.store.let(fromRoot.getBar),
  this.store.let(fromRoot.getFoobar),
  this.store.let(fromRoot.getBarfoo)
)
.debounceTime(300)
.map(([foo, bar, foobar, barfoo]) => {
  ...
});
like image 83
cartant Avatar answered Sep 21 '22 01:09

cartant


With rxjs > v6 you have to use the rxjs pipe function combined with the debounceTime operator e.g.

import {combineLatest, timer} from 'rxjs';
import {debounceTime} from 'rxjs/operators';

function testCombineLatest() {

  const startTime = Date.now();
  const timerOne$ = timer(1000, 1000);
  const timerTwo$ = timer(1300, 1000);

  combineLatest(timerOne$, timerTwo$)
    .pipe(debounceTime(600))
    .subscribe(([timer1, timer2]) => {
      console.log('TimeElapsed:', Date.now() - startTime);
      console.log('Timer Latest:', timer1, timer2);
    });
}
testCombineLatest();
like image 45
guicey Avatar answered Sep 18 '22 01:09

guicey