I've looked around for a way to pass an async function to a Core Data managed object context but can't find anyway yet. I suspect there is some part of the new async/await concurrency model that I am not understanding but I have no idea what it is.
What I'd like to do:
// Grab an moc
let moc = container.newBackgroundContext()
// Enter an async context
Task {
await moc.perform {
// Get some object
let obj = moc.object(with: anObjectID)
// This is not possible because NSManagedObjectContext.perform only accepts
// a synchronous block
await obj.doSomeLongRunningProcess()
}
}
It seems odd to me that this is not possible. I'm not sure if it's just not there yet in the Core Data api because async/await is so new, or if there is a very good reason it's not possible?
Wrapping the doSomeLongRunningProcess in a Task like so
await moc.perform {
Task {
let obj = moc.object(with: anObjectID)
await obj.doSomeLongRunningProcess()
}
}
Doesn't work because the inner Task gets run on a different thread and you end up with CoreData inconsistencies. I was kinda hoping it would inherit the context's thread but this is not the case.
I'd love a way to pass async functions to an ManagedObjectContext, but failing that, I'd like to know why it doesn't/can't work?