WHITECOLOR - 1 year ago 66
Javascript Question

Lasest combination of derived streams

I have 3 streams, one say main stream s1, and two derived streams. I want to get latest combination of this streams.

``````const O = Rx.Observable

let s1\$ = O.from([1,2,3])
let s2\$ = s1\$.map(x => x*10)
let s3\$ = s1\$.map(x => x*100)

let s\$ = O.combineLatest(s1\$, s2\$, s3\$, (s1, s2, s3) => {
//console.log('s1, s2', s1, s2, s3)
return s1 + s2 + s3
})

s\$.subscribe(x => {
console.log('s = ' + x)
})
``````

The output is:

``````"s = 111"
"s = 112"
"s = 122"
"s = 222"
"s = 223"
"s = 233"
"s = 333"
``````

But what I want is:

``````"s = 111"
"s = 222"
"s = 333"
``````

So only last and form s1 and its derived values from s2 and s3. What is the best way to achieve it?

A fiddle:

You have to `share` the s1\$ observable. i.e. your code becomes :

``````console.clear()
const O = Rx.Observable

let s1\$ = O.from([1,2,3]).share()
let s2\$ = s1\$.map(x => x*10).delay(10000)
let s3\$ = s1\$.map(x => x*100)

let s\$ = O.zip(s1\$, s2\$, s3\$, (s1, s2, s3) => {
//console.log('s1, s2', s1, s2, s3)
return s1 + s2 + s3
})

s\$.subscribe(x => {
console.log('s = ' + x)
})
``````

Why is that has been extensively discussed on SO, I encourage to have a look at the distinction between hot and cold observables. It is a key concept of Rx and a common stumbling block for new comers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download