firebase观察数据异步
我正在尝试以异步方式从实时数据库中观察数据。
为此,我使用“ with with CheckedContinature”返回结果,但是我在iOS文档中看到,延续只能是“简历”一次,因此每次我更新数据库中的数据时,都会破坏我的应用程序。
我想知道我正在尝试的方法是可能的,还是还有其他方法可以解决此问题,以使该功能保持异步。
class StoreFirebase {
private let ref = Database.database().reference()
var driverObserver: UInt?
var driverReference: DatabaseReference?
func getDriverSingleLocation(_ uuid: String) async -> Result<StoreData, Error> {
return await withCheckedContinuation { continuation in
driverReference?.observeSingleEvent(of: .value) { (snapshot) in
if let dictionary = snapshot.value as? StoreData {
continuation.resume(returning: .success(dictionary))
} else {
continuation.resume(returning: .failure(HTTPError(.badRequest)))
}
}
}
}
func getDriverLocation(_ uuid: String) async -> Result<StoreData, Error> {
driverReference = ref.child("driversAvailable").child(uuid)
return await withCheckedContinuation { continuation in
var nillableContinuation: CheckedContinuation<Result<StoreData, Error>, Never>? = continuation
driverObserver = driverReference?.observe(.value) { (snapshot) in
if let dictionary = snapshot.value as? StoreData {
nillableContinuation?.resume(returning: .success(dictionary))
} else {
nillableContinuation?.resume(returning: .failure(HTTPError(.badRequest)))
}
}
}
}
}
I am trying to observe data from the Realtime Database in an asynchronous way.
For this I use "withCheckedContinuation" to return the result but I have seen in the IOS documentation that Continuation can only be "resume" once so every time I update the data in the database this breaks my app.
I would like to know if what I am trying is possible or if there is some other way to deal with this problem so that the function remains asynchronous.
class StoreFirebase {
private let ref = Database.database().reference()
var driverObserver: UInt?
var driverReference: DatabaseReference?
func getDriverSingleLocation(_ uuid: String) async -> Result<StoreData, Error> {
return await withCheckedContinuation { continuation in
driverReference?.observeSingleEvent(of: .value) { (snapshot) in
if let dictionary = snapshot.value as? StoreData {
continuation.resume(returning: .success(dictionary))
} else {
continuation.resume(returning: .failure(HTTPError(.badRequest)))
}
}
}
}
func getDriverLocation(_ uuid: String) async -> Result<StoreData, Error> {
driverReference = ref.child("driversAvailable").child(uuid)
return await withCheckedContinuation { continuation in
var nillableContinuation: CheckedContinuation<Result<StoreData, Error>, Never>? = continuation
driverObserver = driverReference?.observe(.value) { (snapshot) in
if let dictionary = snapshot.value as? StoreData {
nillableContinuation?.resume(returning: .success(dictionary))
} else {
nillableContinuation?.resume(returning: .failure(HTTPError(.badRequest)))
}
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
thx发表评论,用异步链修复
Thx for the comment, fixed it with AsyncStream