小编Geo*_*e O的帖子

如何使用 Kotlin 协程运行 Firebase 事务?

我正在尝试在 Kotlin 中的挂起函数下运行 Firebase 事务,但没有看到任何有关它的文档。

我在用着

implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.5.2'
Run Code Online (Sandbox Code Playgroud)

对于带有 firebase 的协程(例如:setValue(*).await() ),但runTransaction(*)似乎没有等待函数

override suspend fun modifyProductStock(
    product: ProductModel,
    valueToModify: Long,
    replace: Boolean
) {
    CoroutineScope(Dispatchers.Main).launch {
        val restaurantId = authRepository.restaurantId.value ?: throw Exception("No restaurant!")

        val productId = product.id ?: throw Exception("No Product ID!")

        val reference = FirebaseDatabase.getInstance().getReference("database/$restaurantId").child("products")

        if (replace) {
            reference.child(productId).child("stock").setValue(valueToModify).await()
        } else {
            reference.child(productId).child("stock")
                .runTransaction(object : Transaction.Handler {

                    override fun doTransaction(p0: MutableData): Transaction.Result {
                        //any operation
                        return Transaction.success(p0)
                    }

                    override fun onComplete(p0: DatabaseError?, p1: Boolean, p2: …
Run Code Online (Sandbox Code Playgroud)

kotlin firebase firebase-realtime-database kotlin-coroutines

4
推荐指数
1
解决办法
449
查看次数