Ios Swift-Firebase是否可以同时进行扇出和运行事务
当同时更新多个引用和运行TransactionBlock时,是否有方法执行原子更新/扇出?下面的代码工作正常,但如果在更新Ios Swift-Firebase是否可以同时进行扇出和运行事务,ios,swift,firebase-realtime-database,Ios,Swift,Firebase Realtime Database,当同时更新多个引用和运行TransactionBlock时,是否有方法执行原子更新/扇出?下面的代码工作正常,但如果在更新updatefollowerscontfunc或updateFollowingCountfunc时出现问题,则计数属性将不正确 将事务添加到扇形输出中将保证一次成功或失败。不过我想不出一个办法 func runFanout() { // currentUser is following otherUser, use fanout to update both ref
updatefollowerscont
func或updateFollowingCount
func时出现问题,则计数属性将不正确
将事务添加到扇形输出中
将保证一次成功或失败。不过我想不出一个办法
func runFanout() {
// currentUser is following otherUser, use fanout to update both refs
let followersRef = "followers/\(otherUserId)/\(currentUserId)"
let followingRef = "following/\(currentUserId)/\(otherUserId)"
var dict = [String: Any]()
dict.updateValue(1, forKey: followersRef)
dict.updateValue(1, forKey: followingRef)
let rootDbRef = Database.database().reference()
rootDbRef.updateChildValues(dict, withCompletionBlock: { (error, ref) in
if let error = error { return }
self.updateFollowersCount(for: otherUserId)
self.updateFollowingCount(for: currentUserId)
})
}
func updateFollowersCount(for userId: String) {
let followersCount = Database.database().reference().child("users").child(userId)
followersCount.runTransactionBlock({ (currentData: MutableData) -> TransactionResult in
if var dict = currentData.value as? [String: Any] {
var count = dict["followers_count"] as? Int ?? 0
count += 1
dict["followers_count"] = count
currentData.value = dict
}
return TransactionResult.success(withValue: currentData)
}, andCompletionBlock: { [weak self](error, completion, snap) in
if !completion || (error != nil) {
print("The value wasn't able to update")
} else {
print("The value updated")
}
})
}
func updateFollowingCount(for userId: String) {
let followingCount = Database.database().reference().child("users").child(userId)
followingCount.runTransactionBlock({ (currentData: MutableData) -> TransactionResult in
if var dict = currentData.value as? [String: Any] {
var count = dict["following_count"] as? Int ?? 0
count += 1
dict["following_count"] = count
currentData.value = dict
}
return TransactionResult.success(withValue: currentData)
}, andCompletionBlock: { [weak self](error, completion, snap) in
if !completion || (error != nil) {
print("The value wasn't able to update")
} else {
print("The value updated")
}
})
}