Search code examples
angularfirebaserxjsangularfire2subscription

Angularfire rxjs multiple subscriptions


I have an angularfire function which queries Firestore for collections in which there are many possible collections.

I loop through my list which contains search query endpoints, and then call the search function which queries firebase and returns the collections. I feel this is not proper use of RXJS.

Currently the loop subscribes to a new firebase observer on every loop. I feel this is not best practice and that it could be done in a better way.

Is there a way to create one subscription but still pass all the downloaded data?

for (let item of list) {
    searchMap('enpoint')
      .subscribe((data) => {
        this.skillResults = this.skillResults.concat(data);
      })
  }
}

searchMap(endpoint) {
    return return this.angularfire.collection('bucket/' + endpoint).valueChanges()
}

Solution

  • You could use forkJoin or zip for this:

    const observables = list.map(item => searchMap('enpoint'));
    
    Observable.forkJoin(observables).subscribe(...)
    

    However, the forkJoin operator requires all source Observables to complete which is probably not what happens with valueChanges() so you can chain each Observable with take(1).

    const observables = list.map(item => searchMap('enpoint').take(1));
    

    Or you might use zip if you expect the source Observables to emit the same number of items:

    Observable.zip(...observables).take(1).subscribe(...)
    

    Maybe also have a look at the combineLatest operator but it really depends on what you want to do.