When working with Firestore, I need to retrieve multiple documents, each with a unique sourceAddressValue. This means for a list of N strings, I may need to fetch N documents.
I attempted the following approach:
getLocationAddresses(addresses: string[]) {
const chunkSize = 10;
let addressesChunks = [];
if (addresses.length < chunkSize) {
addressesChunks.push(addresses);
} else {
addressesChunks = [...Array(Math.ceil(addresses.length / chunkSize))].map(_ => addresses.splice(0,chunkSize));
}
console.log(addressesChunks);
return of(...addressesChunks).pipe(
mergeMap<string[], any>((x) => this.db.collection('locations', ref =>
ref.where('sourceLocation', 'array-contains', x)).valueChanges()),
toArray() // when this is removed, the code inside getOrders is triggered multiple times
);
}
public getOrders() {
this.getJSON().subscribe(data => {
this.orders = data.orders;
const addresses = this.orders.map(item => `${item.address}, ${item.postalCode}`);
this.dbService.getLocationAddresses(addresses).subscribe(data => {
console.log('data retrieved');
console.log(data);
});
this.ordersRefreshed.next(this.orders);
});
}
However, it appears that the execution of the code is incomplete. Interestingly, when I remove the toArray() from getLocationAddresses, the subscribed function is triggered multiple times, once for each chunk.
Is there a way to group multiple completions of an observable function so that the observer is only fired once?