left4bread
left4bread

Reputation: 1634

Angular 2 – Acting on two BehaviorSubject / Observables

Suppose I have a component which needs two observables to render its content:

this.manifest.subscribe((a) => {
    f(a, b) 
})

this.route.params.subscribe((b) => {
    f(a, b)
})

What is the proper Angular / rxjs way to call f() once a arrives, and / or call it again once b (e.g., update on routing params) arrives.

Obviously I could keep track of a and b manually, but that looks ugly and not elegant. Is there a more Angularian way?

Upvotes: 1

Views: 1003

Answers (2)

paulpdaniels
paulpdaniels

Reputation: 18663

You can use combineLatest to merge the two streams and fire each time one of them fires.

Rx.Observable.combineLatest(this.manifest, this.route.params, (a, b) => f(a, b))
  .subscribe(c => /*Do something with the result of f(a,b)*/

Note that the above only fires once it has at least one value from each source, but I don't think that should be a problem if your sources are BehaviorSubjects

Upvotes: 3

Alexander Ciesielski
Alexander Ciesielski

Reputation: 10834

If you need two observables to resolve one after the other you might want to consider Observable.concat(obs1, obs2).

When subscribing to the concatenated observable, obs1 will be subscribed to first, and then obs2.

Upvotes: 0

Related Questions