Search code examples
typescriptfiltertoarray

Observable switchMap filter toArray


I'm trying to filter episodes with switchMap & filter :

this.getEpisodesForStoryEvents()
    .switchMap(episodes => Observable.from(episodes))
    .filter((episode: Episode) => {
        return episode.ref.startsWith('SE/8');
    })
    .toArray()
    .subscribe(episodes => {
        console.log(episodes);
    });

But when using toArray, it doesn't work anymore, I don't subscribe to anything :/


Solution

  • Your problem is that valueChanges is an event emitter. I assume it emits an event every time that collection changes. There can always be more changes, so valueChanges never calls complete, and toArray waits forever.

    You can't use toArray here. Must subscribe to the observable and process each entry as it comes. Or you could use reduce and add the items to an array yourself. Only that reduce is called for every new value pushed into the source observable, so you get updated with every change that passes the filter