I had a situation where I mistakenly prevented my firebase rules from writing to a ref and when I ran the code below "The value wasn't able to update, try again" printed out over 20x. The way I'm doing it now the transaction keeps trying itself until it's successful but after what I just encountered if it's not successful the transaction will run forever.
I was wondering is there a built in way to run a max # of tries if the transaction fails?
func runTransaction(on userId: String) {
self.followButton.isEnabled = false
let followersPath = Database.database().reference()
.child("users")
.child(userId)
.child("followersCount")
followersPath.runTransactionBlock({ (mutableData: MutableData) -> TransactionResult in
var currentCount = mutableData.value as? Int ?? 0
mutableData.value = currentCount + 1
return TransactionResult.success(withValue: mutableData)
}, andCompletionBlock: { (error, completion, snap) in
if !completion || (error != nil) {
print("The value wasn't able to update, try again")
self.runTransaction(on: userId)
return
}
print("The value updated")
let totalFollowersCount = snap?.value as? Int ?? 0
self.myCellWithTheUserId.followersCount = totalFollowersCount
self.followButton.isEnabled = true
})
}