Last active
December 19, 2018 10:03
-
-
Save kikermo/6a75f6ffce6c4980ed1a697a062829de to your computer and use it in GitHub Desktop.
Get firebase paginated list
This file contains 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
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