Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firestore live update using Kotlin Flow

I want to implement system with live updates (similar to onSnapshotListener). I heard that this can be done with Kotlin Flow.

Thats my function from repository.

 suspend fun getList(groupId: String): Flow<List<Product>> = flow {
        val myList = mutableListOf<Product>()
        db.collection("group")
            .document(groupId)
            .collection("Objects")
            .addSnapshotListener { querySnapshot: QuerySnapshot?,
                                   e: FirebaseFirestoreException? ->
                if (e != null) {}
                querySnapshot?.forEach {
                    val singleProduct = it.toObject(Product::class.java)
                    singleProduct.productId = it.id
                    myList.add(singleProduct)
                }
            }
       emit(myList)
    }

And my ViewModel

class ListViewModel: ViewModel() {

private val repository = FirebaseRepository()
private var _products = MutableLiveData<List<Product>>()
val products: LiveData<List<Product>> get() = _produkty


init {
    viewModelScope.launch(Dispatchers.Main){
        repository.getList("xGRWy21hwQ7yuBGIJtnA")
            .collect { items ->
                _products.value = items
            }
    }
}

What do I need to change to make it work? I know data is loaded asynchronously and it doesn't currently work (the list I emit is empty).

like image 956
Simon Avatar asked Oct 13 '25 03:10

Simon


1 Answers

Starting in firestore-ktx:24.3.0, you can use the Query.snapshots() Kotlin flow to get realtime updates:

suspend fun getList(groupId: String): Flow<List<Product>> {
    return db.collection("group")
            .document(groupId)
            .collection("Objects")
            .snapshots().map { querySnapshot -> querySnapshot.toObjects()}
}
like image 172
Rosário Pereira Fernandes Avatar answered Oct 15 '25 22:10

Rosário Pereira Fernandes