Combine the outputs of two observables in to one output array in RxJs

Google Firestore doesn’t support OR queries so you have to run two queries and then combine them. This proved a little tricker than I had anticipated as I needed the output of another observable fed into both of them (the usersId).

The solution sets up two observable chains (that are disappointingly similar – refactor required!) and then uses combineLatest and then a simple map to get the outputs into one array.

getCombinedArrays(): Observable {

    const obs1 = from(this.afAuth.currentUser.then(user => {
      return user.uid;
    }))
    .pipe(
      switchMap(
          userid => {
          return this.db.collection('friendships', ref => ref.where('field1', '==', userid)).snapshotChanges().pipe(map(actions => {
            //returns customClass array after some Firebase faff
          }));
        }
      )
    );

    const obs2 = from(this.afAuth.currentUser.then(user => {
      return user.uid;
    }))
    .pipe(
      switchMap(
          userid => {
          return this.db.collection('friendships', ref => ref.where('field2', '==', userid)).snapshotChanges().pipe(map(actions => {
            //returns customClass array after some Firebase faff
          }));
        }
      )
    );

    return combineLatest([obs1, obs2]).pipe(
      map(([results1, results2]) => {
        const combinedResults = [...results1, ...results2];
        return combinedResults;
      })
   );
   
}