I want to implement this pattern in my app:
let moc = ...newBackgroundContext()
try await moc.perform {
// test for existence of a specific object in the moc
if !objectExists {
let apiObject = await api.fetchObjectFromNetwork()
// create managed object from apiObject
try moc.save()
}
}
Unfortunately, I am unable to await
my network call because the moc.perform
block is not async.
So far, I've come up with this solution:
let moc = ...newBackgroundContext()
try await moc.perform {
// test for existence of a specific object in the moc
if !objectExists {
Task {
let apiObject = await api.fetchObjectFromNetwork()
try await moc.perform {
// create managed object from apiObject
try moc.save()
}
}
}
}
But it doesn't feel quite right.
What do you think? Am I on the right track, or am I introducing unneeded complexity?