Skip to content

Instantly share code, notes, and snippets.

@SUPERCILEX
Last active October 4, 2017 03:40
Show Gist options
  • Save SUPERCILEX/7fe920be9b24eb818a1becab3be8c3b0 to your computer and use it in GitHub Desktop.
Save SUPERCILEX/7fe920be9b24eb818a1becab3be8c3b0 to your computer and use it in GitHub Desktop.
// Please don't actually use this method, it's just a nice example of how painful the listener registration API is.
// I wrote it with a case of YAGNI before I really understood the Firestore APIs—you should
// be using `Query#get()` if you need the most up-to-date copy of your documents.
fun Query.getFromServer(): Task<QuerySnapshot> = TaskCompletionSource<QuerySnapshot>().apply {
val listener = object : EventListener<QuerySnapshot> {
lateinit var registration: ListenerRegistration
override fun onEvent(snapshot: QuerySnapshot?, e: FirebaseFirestoreException?) {
if (e == null) {
if (!snapshot!!.metadata.isFromCache) {
setResult(snapshot)
registration.remove()
}
} else {
FirebaseCrash.report(e)
setException(e)
registration.remove()
}
}
}
listener.registration = addSnapshotListener(
QueryListenOptions().includeQueryMetadataChanges(),
listener)
}.task
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment