Skip to content

Instantly share code, notes, and snippets.

@SUPERCILEX
Last active October 4, 2017 03:41
Show Gist options
  • Save SUPERCILEX/dad6effe480069a34e329b945ddb120a to your computer and use it in GitHub Desktop.
Save SUPERCILEX/dad6effe480069a34e329b945ddb120a to your computer and use it in GitHub Desktop.
/** Deletes all scouts for a team, including their `metrics` subcollection. */
fun Team.deleteAllScouts() {
ref.collection("scouts").delete() // Kotlin's syntactic sugar
.addOnSuccessListener { snapshots: List<DocumentSnapshot> ->
for (snapshot in snapshots) deleteScout(snapshot.id)
}
}
fun Team.deleteScout(id: String) {
val scoutDoc = ref.collection("scouts").document(id)
scoutDoc.delete() // Native document deletion
scoutDoc.collection("metrics").delete() // Kotlin's syntactic sugar
}
/**
* Delete all documents in a collection. This does **not** automatically discover and delete
* sub-collections.
*/
fun CollectionReference.delete(batchSize: Long = 100): Task<List<DocumentSnapshot>> = async {
val deleted = ArrayList<DocumentSnapshot>()
var query = orderBy(FieldPath.documentId()).limit(batchSize)
var latestDeleted = deleteQueryBatch(query)
deleted += latestDeleted
while (latestDeleted.size >= batchSize) {
query = orderBy(FieldPath.documentId()).startAfter(latestDeleted.last()).limit(batchSize)
latestDeleted = deleteQueryBatch(query)
}
deleted as List<DocumentSnapshot>
}
/** Delete all results from a query in a single [WriteBatch]. */
@WorkerThread
private fun deleteQueryBatch(query: Query): List<DocumentSnapshot> = Tasks.await(query.get()).let {
Tasks.await(firestoreBatch {
for (snapshot in it) delete(snapshot.reference)
})
it.documents
}
inline fun <T> async(crossinline block: () -> T): Task<T> =
AsyncTaskExecutor.execute(Callable { block() })
object AsyncTaskExecutor : Executor {
private val service = Executors.newCachedThreadPool()
fun <TResult> execute(callable: Callable<TResult>): Task<TResult> = Tasks.call(this, callable)
override fun execute(runnable: Runnable) {
service.submit(runnable)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment