Use Kotlin coroutines for real time Firestore updates

Viewed 697

When fetching one-time data from Firestore, I can remove callbacks using the kotlinx-coroutines-play-services library:

Using callbacks

firestore.collection("Users")
    .document(userId)
    .get()
    .addOnSuccessListener { snapshot ->
        // Handle snapshot
    }
    .addOnFailureListener { exception ->
        // Handle exception
    }

Using await() and coroutine

try {
    val snapshot = firestore.collection("Users")
        .document(userId)
        .get().await()
    // Handle snapshot
} catch(exception: Exception) {
    // Handle error
}

I'm looking for a similar approach for real time updates. Is there an await() equivalent for addSnapshotListener()?

firestore.collection("Users")
    .document(userId)
    .addSnapshotListener { snapshot, exception ->
        // Listen to snapshot in real time
    }
1 Answers

Firestore listeners are not fundamentally compatible with coroutines, because they don't generate a single item for consumption. You can't "await" a sequence of callbacks that happen over time (that have no distinct point of termination).

The most natural Kotlin concept that maps to listeners is flow. A flow can produce a sequence of values over time, and you can consume them in a coroutine context if you wish. You will have to write some code to convert that listener into a flow (search those keywords to see what others have done).

Related