使用 Kotlin Flow 实时更新 Firestore

Sim*_*mon 4 android kotlin firebase google-cloud-firestore kotlin-flow

我想实现具有实时更新的系统(类似于 onSnapshotListener)。我听说这可以用Kotlin Flow来完成。

这是我来自存储库的函数。

 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)
    }
Run Code Online (Sandbox Code Playgroud)

还有我的视图模型

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
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要改变什么才能让它发挥作用?我知道数据是异步加载的,并且当前不起作用(我发出的列表为空)。

Ros*_*des 9

firestore-ktx:24.3.0开始,您可以使用Query.snapshots() Kotlin 流程来获取实时更新:

suspend fun getList(groupId: String): Flow<List<Product>> {
    return db.collection("group")
            .document(groupId)
            .collection("Objects")
            .snapshots().map { querySnapshot -> querySnapshot.toObjects()}
}
Run Code Online (Sandbox Code Playgroud)


Arp*_*kla 8

您可以使用我在项目中使用的扩展函数:

fun Query.snapshotFlow(): Flow<QuerySnapshot> = callbackFlow {
    val listenerRegistration = addSnapshotListener { value, error ->
        if (error != null) {
            close()
            return@addSnapshotListener
        }
        if (value != null)
            trySend(value)
    }
    awaitClose {
        listenerRegistration.remove()
    }
}
Run Code Online (Sandbox Code Playgroud)

它使用callbackFlow构建器创建一个新的流实例。

用法:

fun getList(groupId: String): Flow<List<Product>> {
    return db.collection("group")
        .document(groupId)
        .collection("Objects")
        .snapshotFlow()
        .map { querySnapshot ->
            querySnapshot.documents.map { it.toObject<Product>() }
         }
}
Run Code Online (Sandbox Code Playgroud)

请注意,您不需要标记getListsuspend