EduBic
EduBic

Reputation: 347

RxJs6 - Static merge an array of observables

I have a list of objects created dynamically by the user. Each object has a click$ observable, I want to merge all this click$ streams in one stream.

I've tried the merge static operator from rxjs import. With the direct references to the stream:

sub = merge(list[0].click$, list[1].click$)
    .subscribe(e => { 
       console.log('My click event', e); 
    })

all goes as expected.

But when I use an array of click$ in the subscribe next call I received an Observable object and not my click event.

const streams= [];
list.forEach(o => { streams.push(o.click$); });

sub = merge(streams).subscribe(e => {
  console.log(e); // e is an observable ???
});

Why? What am I doing wrong?

Here a similar implementation with the same error: https://stackblitz.com/edit/typescript-ohq6rx?file=index.ts&devtoolsheight=100

Upvotes: 0

Views: 409

Answers (1)

Murf
Murf

Reputation: 1719

Since it's an array. You can spread an array with the ... operator in JavaScript. If you do this all should work well.

More information can be found at MDN

I added code so you have an idea what I mean. List is the array of objects that have click$ properties. this array is mapped to just the click$ and then spread with the ... operator.

sub = merge(...list.map(item => item.click$)).subscribe(console.log)

Upvotes: 1

Related Questions