Created
January 2, 2018 18:00
-
-
Save HarryTylenol/8619aa91c72e0f467396be720842c1ec to your computer and use it in GitHub Desktop.
Nice Kotlin Extensions for Google Firestore
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
fun test() { | |
class City(var name: String, var location: GeoPoint) | |
var query = FirebaseFirestore.getInstance().collection("city").limit(10) | |
var error : (Exception) -> Unit = { it.printStackTrace() } | |
query.query<City>(callbackWithKey = { keyList, cityList -> }, error = error) | |
query.query(callback = { documentSnapshotList -> }, error = error) | |
query.addChangeListener(isAdded = {}, isRemoved = {}, isModified = {}, error = error) | |
} | |
infix fun <T : Any> DocumentSnapshot.convertAs(classType: Class<T>) = toObject(classType) | |
inline fun <reified T : Any> Query.query(crossinline callbackWithKey: (List<String>, List<T>) -> Unit, crossinline error: (Exception) -> Unit = { it.printStackTrace() }) { | |
get().addOnSuccessListener { | |
callbackWithKey(it.documents.map { it.id }, it.documents.map { it convertAs T::class.java }) | |
}.addOnFailureListener { | |
error(it) | |
} | |
} | |
inline fun Query.query(crossinline callback: (List<DocumentSnapshot>) -> Unit, crossinline error: (Exception) -> Unit = { it.printStackTrace() }) { | |
get().addOnSuccessListener { | |
callback(it.documents) | |
}.addOnFailureListener { | |
error(it) | |
} | |
} | |
inline fun Query.addChangeListener( | |
crossinline isAdded: (DocumentSnapshot) -> Unit, | |
crossinline isRemoved: (DocumentSnapshot) -> Unit, | |
crossinline isModified: (DocumentSnapshot) -> Unit, | |
crossinline error: (Exception) -> Unit = { it.printStackTrace() }) { | |
addSnapshotListener { querySnapshot, fe -> | |
if (fe != null || querySnapshot == null) { | |
error(fe) | |
return@addSnapshotListener | |
} | |
querySnapshot.documentChanges.forEach { | |
when (it.type) { | |
DocumentChange.Type.ADDED -> isAdded(it.document) | |
DocumentChange.Type.REMOVED -> isRemoved(it.document) | |
DocumentChange.Type.MODIFIED -> isModified(it.document) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment