Skip to content

Instantly share code, notes, and snippets.

val teamsQuery get() = "owners.${uid!!}".let {
FirebaseFirestore.getInstance().collection("teams").whereGreaterThanOrEqualTo(it, 0).orderBy(it)
}
object TeamsLiveData : LiveData<ObservableSnapshotArray<T>>(), FirebaseAuth.AuthStateListener {
init {
FirebaseAuth.getInstance().addAuthStateListener(this)
}
override fun onAuthStateChanged(auth: FirebaseAuth) {
"owners.$uid".let {
FirebaseFirestore.getInstance().collection("teams").whereGreaterThanOrEqualTo(it, 0).orderBy(it)
}
FirebaseFirestore.getInstance().collection("teams").whereEqualTo("owners.$uid", true)
// Please don't actually use this method, it's just a nice example of how painful the listener registration API is.
// I wrote it with a case of YAGNI before I really understood the Firestore APIs—you should
// be using `Query#get()` if you need the most up-to-date copy of your documents.
fun Query.getFromServer(): Task<QuerySnapshot> = TaskCompletionSource<QuerySnapshot>().apply {
val listener = object : EventListener<QuerySnapshot> {
lateinit var registration: ListenerRegistration
override fun onEvent(snapshot: QuerySnapshot?, e: FirebaseFirestoreException?) {
if (e == null) {
if (!snapshot!!.metadata.isFromCache) {
FirebaseFirestore.getInstance()
.collection("teams")
.addSnapshotListener { snapshot: QuerySnapshot?, e: FirebaseFirestoreException? ->
if (e != null) {
FirebaseCrash.report(e)
return@addSnapshotListener
}
snapshot!! // The parameters follow a XOR pattern so this is perfectly safe
// Do stuff
/** 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)
fun Team.addScout() {
val scoutRef: DocumentReference = FirebaseFirestore.getInstance()
.collection("teams")
.document(id /* Field in Team */)
.collection("scouts")
.document() // Creating a document ref with a truly random id
scoutRef.set(Scout(scoutRef.id, templateId))
firestoreBatch {
val metricsRef = scoutRef.collection("metrics")
FirebaseFirestore.getInstance().collection("teams").add(team)
{
"teams": { // Collection
"teamId1": { // Document
"name": "SERT",
"number": 2521,
"owners": { // Object within document
"uid1": 2521, // We sort our teams in ascending order by team number
"uid2": { ... },
"uid3": { ... }
},
{
"team-indices": {
"uid1": {
"teamKey1": 2521, // We sort our teams in ascending order by team number
"teamKey2": { ... },
"teamKey3": { ... }
},
"uid2": { ... },
"uid3": { ... }
},