Last active
December 19, 2018 08:39
-
-
Save kikermo/4b869b9eaf5f9964f6362f665fdfed55 to your computer and use it in GitHub Desktop.
Simple List Fetching using Firebase Firestore and RxJava
This file contains hidden or 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.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