Skip to content

Instantly share code, notes, and snippets.

@HarryTylenol
Created January 2, 2018 18:00
Show Gist options
  • Save HarryTylenol/8619aa91c72e0f467396be720842c1ec to your computer and use it in GitHub Desktop.
Save HarryTylenol/8619aa91c72e0f467396be720842c1ec to your computer and use it in GitHub Desktop.
Nice Kotlin Extensions for Google Firestore
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