How to combine multiple Observables together in Angular 2

mshantic picture mshantic · Jul 14, 2016 · Viewed 10k times · Source

So I've just started programming with Angular 2 and just got started on learning about subscribe, Subject and BehaviorSubject. Currently I have multiple subscriptions to obtain values stored in my service and emitted to a component. My application works and all but I know it is very inefficient. That it has gotten out of hand in my component:

this.threatService.minLimitChange$.subscribe( min => { this.min = min; this.getSession();});
this.threatService.maxLimitChange$.subscribe( max => { this.max = max; this.getSession();});

(and like 5 other more that obtains a single value and calls function getSession() each time)

In my threat.service:

private minLimitChangeSource = new BehaviorSubject<number>(this.min);
private maxLimitChangeSource = new BehaviorSubject<number>(this.max);
minLimitChange$ = this.minLimitChangeSource.asObservable();
maxLimitChange$ = this.maxLimitChangeSource.asObservable();

So I've tried:

this.threatService.minLimitChange$.concat(this.threatService.maxLimitChange$).subscribe( res => console.log(res));

Which my aim was just to test what res was because I wasn't sure how to access the two values... but I'm getting this in my console. ;/

TypeError: this.threatService.minLimitChange$.merge is not a function. (In 'this.threatService.minLimitChange$.concat(this.threatService.maxLimitChange$)', 'this.threatService.minLimitChange$.concat' is undefined)

Ultimately, I'd like to get all values that getSession() needs from my service and run that function once. I would really appreciate any help or explanation on how to use concat, merge or forkJoin to combine my subscriptions please. Thank you!

Answer

Harry Ninh picture Harry Ninh · Jul 14, 2016

You can use Observable.combineLatest to combine 2 observable streams into one:

combineObs = obs1.combineLatest(obs2, 
  (val1, val2) => { 
    return {val1: val1, val2: val2};
  });

Working plunker: http://plnkr.co/edit/mmCzEmdKexpaWNM53me9?p=preview