FireStore事务递增和递减计数器获得不一致的结果

时间:2017-11-26 18:33:57

标签: android firebase transactions kotlin google-cloud-firestore

以下是交易代码: -

var sfDocRef = firebaseCloudStore.collection("New").document(documentRef.get(pos))
    firebaseCloudStore.runTransaction(Transaction.Function {
        transaction - >
            val snapshot = transaction.get(sfDocRef)
        var newlikes: Double

        if (isliked == true) {
            newlikes = snapshot.getDouble("likes") !!+1
        } else {
            newlikes = snapshot.getDouble("likes") !!-1
        }
        transaction.update(sfDocRef, "likes", newlikes)
    }).addOnSuccessListener {

        var ref = firebaseCloudStore.collection("New").document(documentRef.get(pos)).get().addOnCompleteListener {
            list = it.result.toObject(New::class.java)
            arraylist.get(pos).likes = list.likes
            arraylist.get(pos).isliked = !arraylist.get(pos).isliked
            adapter.notifyItemChanged(pos)

        }
    }.addOnFailureListener(OnFailureListener {
        e - > Log.w("TAG", "Transaction failure.", e)
    })

这里我已经实现了文档中提到的F​​ireStore事务,但仍然得到了不一致的结果,就像你反复快速按下按钮一样,结果要么更大,要么更少。代码中是否有错误或我做错了什么?

1 个答案:

答案 0 :(得分:0)

也许您必须在return null方法中添加Transaction.Function.apply(),例如this