Fruff
Fruff

Reputation: 47

Create Observable that behaves like CombineLatest but only emit the value of the source that just fired

I would like to create an observable which takes N observable sources and transform them whith an N-ary function. The onNext() of this observable will call this function whenever one of the source observables emits an item, like this: f(null,null,null,o3.val,null,null) where o3 is the source which just emitted a value.

Is like the combineLatest where the f is called with the last emitted values from all the sources combined together but here in the f we get null value for all the others.

The body of the f could act like a switch:

 function f(v1,v2,...vn) {
        if (v1) { ... }
        else if(v2) { ... }
    }

Is this possible? There are other way round for accomplish this behaviour?

Upvotes: 1

Views: 400

Answers (1)

Picci
Picci

Reputation: 17762

You may want to think about something like this

const obsS1 = obsSource1.pipe(map(data => [data, 'o1']));
const obsS2 = obsSource2.pipe(map(data => [data, 'o2']));
....
const obsSN = obsSourceN.pipe(map(data => [data, 'oN']));

merge(obs1, obs2, ..., obsN)
.subscribe(
  dataObs => {
    // do what you need to do
    // dataObs[0] contains the value emitted by the source Observable
    // dataObs[1] contains the identifier of the source Observable which emitted last
  }
)

Upvotes: 2

Related Questions