Concat two observables for firestore query on multiple fields

Viewed 144

I am trying to get a user search functionality working in my AngularFire app. As firestore doesn't support these queries I thought it would be enough to query the fields separately

getUsersByName(searchValue: string) {
    const firstNames = this.afs.collection<IUser>('user', ref => ref.orderBy('firstname').startAt(searchValue).endAt(searchValue+'\uf8ff')).valueChanges({ idField: 'id' });
    const lastNames = this.afs.collection<IUser>('user', ref => ref.orderBy('lastname').startAt(searchValue).endAt(searchValue+'\uf8ff')).valueChanges({ idField: 'id' });
    return concat(firstNames, lastNames);
  }

This only works for the firstNames though. Only the first Observable is being used. I think I don't understand the concat operator but it's not clear to me according the docs what the current best solution would be for this problem.

2 Answers

The reason this only works for first name is because of how concat works; it will only use one observable at a time until it completes, but the firestore observables are long lived and will not complete.

You should use merge instead of concat.

import { merge } from 'rxjs';

getUsersByName(searchValue: string) {
    const firstNames = this.afs.collection<IUser>('user', ref => ref.orderBy('firstname').startAt(searchValue).endAt(searchValue+'\uf8ff')).valueChanges({ idField: 'id' });
    const lastNames = this.afs.collection<IUser>('user', ref => ref.orderBy('lastname').startAt(searchValue).endAt(searchValue+'\uf8ff')).valueChanges({ idField: 'id' });
    return merge(firstNames, lastNames);
  }
Related