简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM