0

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 :/

Menencia
  • 1,289
  • 1
  • 12
  • 23
  • `toArray` only executes when the source observable completes. Are you sure that happens? Can you post the code of `this.getEpisodesForStoryEvents`? – Oscar Paz Mar 28 '18 at 14:05
  • `return this.db.collection('episodes-se').valueChanges();` - I'm using firebase actually. – Menencia Mar 28 '18 at 14:12

2 Answers2

1

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

Oscar Paz
  • 18,084
  • 3
  • 27
  • 42
0

Maybe it's a late answer :)
but simple solution for the problem can be :

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

So I just encapsulate the filter and toArray inside the switchMap