Skip to content

Instantly share code, notes, and snippets.

@kikermo
Last active December 19, 2018 08:39
Show Gist options
  • Save kikermo/4b869b9eaf5f9964f6362f665fdfed55 to your computer and use it in GitHub Desktop.
Save kikermo/4b869b9eaf5f9964f6362f665fdfed55 to your computer and use it in GitHub Desktop.
Simple List Fetching using Firebase Firestore and RxJava
inline fun <reified FirebaseObject : FirebaseIdentifiableModel> FirebaseFirestore.getSimpleFirebaseList(
path: String
): Single<List<FirebaseObject>> = Single.create<List<FirebaseObject>> { emitter ->
val listenerRegistration: ListenerRegistration = collection(path).addSnapshotListener { querySnapshot, exception ->
querySnapshot?.run {
emitter.onSuccess(toFirebaseObjectList())
} ?: exception?.run {
emitter.onError(this)
} ?: kotlin.run { emitter.onError(FirebaseUnexpectedException()) }
}
emitter.setCancellable { listenerRegistration.remove() }
}
inline fun <reified FirebaseObject : FirebaseIdentifiableModel> QuerySnapshot.toFirebaseObjectList(): List<FirebaseObject> =
this.documents.map { documentSnapshot ->
documentSnapshot.toObject(FirebaseObject::class.java)?.apply {
id = documentSnapshot.id
} as FirebaseObject
}
abstract class FirebaseIdentifiableModel(
@Exclude var id: String = ""
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment