Created
April 29, 2020 12:14
-
-
Save automaticalldramatic/797f67ec947234913a43ec55e5af8578 to your computer and use it in GitHub Desktop.
Gists for the post - https://rizwaniqbal.com/posts/paginating-firestore-collections-with-snapshot-listeners/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface ObservablePaginatedResult { | |
cards: Observable<Array<SomeCards>>; | |
stop: () => void; | |
} | |
// returns an observable to subscribe to for changes and a method to stop listening to the snapshot | |
public SyncCards(pageSize: number = this.DefaultPageSize): <ObservablePaginatedResult> { | |
// an internal subject to handle streaming until the connection is closed. The buffer size of 1 fits my scenario and is up to the readers discretion | |
const cards$: ReplaySubject<Array<SomeCards>> = new ReplaySubject<SomeCards[]>(1); | |
// create a query for Firestore | |
const query = this.cardsCollRef.orderBy('priority', 'desc').limit(pageSize); | |
// create a snapshot query to get cards in descending priority | |
const stopListening = query.onSnapshot((cardSnapshot) => { | |
const cards: SomeCards[] = []; | |
cardSnapshot.forEach((cardDoc) => { | |
cards.push(cardDoc.data() as SomeCards); | |
}); | |
cards$.next(cards); | |
}); | |
return {cards: cards$.pipe(distinctUntilChanged()), stop: stopListening}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment