使用异步和等待从错误的线程访问Realm



运行下面的代码,我得到"从错误的线程访问领域"第二try! realm.write({线上的错误,则第一写入线不会引起错误。你知道怎么修吗?

let realm = try! await Realm()
print("User Realm User file location: (realm.configuration.fileURL!.path)")
try! realm.write { // <= No error here
realm.add(groups, update: .modified)
}
StartApp._Groups = groups
if let items  = await api.getArticles(aricleIDs: ids) {
try! realm.write({ // <= Error here
realm.add(items, update: .modified)
})
StartApp._Items = items
var index = 0
StartApp._Items = StartApp.Items.map { item in
item.i = index
index = index + 1
return item
}
groups.forEach { group in
group.items = items.filter({ $0.groupId == group.id })
}
}

i修复了以下问题,删除了wait Realm((并将写入合并到一个中

DispatchQueue.main.async{
do {
let realm = try Realm()

var index = 0
items.forEach { item in
item.i = index
index = index + 1
}
try realm.write({
realm.add(groups, update: .modified)
realm.add(items, update: .modified)
}
})
} catch {
print("Realm error: (error)")
}
}

问题是在初始化Realm时使用await,这基本上是说在一些OTHER异步上下文上实例化领域并返回。即使这是可能的,也没有必要。领域初始值设定项不是异步的。

要求领域在实例化的同一异步上下文(线程(上完成事务。通过用withCheckedContinuation函数(还有一个抛出函数withCheckedThrowingContinuation(将实例化和事务封装在一块代码中,异步等待可以确保这一点。点击此处阅读更多

以下是它的外观:

public func loadSomething(with id: String) async throws -> Something {
let result = try await withCheckedThrowingContinuation { continuation in
do {
let realm = try Realm()
guard let something = realm.object(ofType: DBSomething.self, forPrimaryKey: id) else {
throw YourError.somethingHappened
}
continuation.resume(with: something)
} catch {
continuation.resume(with: .failure(error))
}
}
return result
}

最新更新