Skip to content

Instantly share code, notes, and snippets.

@kikermo
Created December 19, 2018 09:48
Show Gist options
  • Save kikermo/17cf1b4cddb179b5f96326338db2311e to your computer and use it in GitHub Desktop.
Save kikermo/17cf1b4cddb179b5f96326338db2311e to your computer and use it in GitHub Desktop.
Firestore first document retrieving for pagination
fun FirebaseFirestore.getFirstDocument(
path: String,
page: FirebasePage
): Maybe<DocumentSnapshot> = Maybe.create { emitter ->
val collectionReference = collection(path)
.orderBy(page.orderBy, page.direction)
.limit(page.size * page.number + 1)
val listenerRegistration: ListenerRegistration = collectionReference.addSnapshotListener { querySnapshot, exception ->
querySnapshot?.run {
if (size() > page.size * page.number) {
val firstDocument = documents[size() - 1]
emitter.onSuccess(firstDocument)
} else {
emitter.onComplete()
}
} ?: exception?.run {
emitter.onError(this)
} ?: kotlin.run { emitter.onError(FirebaseUnexpectedException()) }
}
emitter.setCancellable { listenerRegistration.remove() }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment