Skip to content

Instantly share code, notes, and snippets.

@kikermo
Last active December 19, 2018 10:03
Show Gist options
  • Save kikermo/6a75f6ffce6c4980ed1a697a062829de to your computer and use it in GitHub Desktop.
Save kikermo/6a75f6ffce6c4980ed1a697a062829de to your computer and use it in GitHub Desktop.
Get firebase paginated list
inline fun <reified FirebaseObject : FirebaseIdentifiableModel> FirebaseFirestore.getPaginatedFirebaseList(
path: String,
page: FirebasePage
): Single<List<FirebaseObject>> {
val firstDocumentMaybe = getFirstDocument(path, page)
return firstDocumentMaybe.isEmpty.flatMap {
return@flatMap if (it) {
Single.just(emptyList())
} else {
firstDocumentMaybe.flatMapSingle { firstDocument ->
return@flatMapSingle Single.create<List<FirebaseObject>> { emitter ->
val collectionReference = collection(path).orderBy(page.orderBy, page.direction)
.startAt(firstDocument)
.limit(page.size)
val listenerRegistration: ListenerRegistration = collectionReference.addSnapshotListener { querySnapshot, exception ->
querySnapshot?.run {
emitter.onSuccess(toFirebaseObjectList())
} ?: 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