So I do not know methods to carry out SwiftData operations on a background thread. Each time I name my @ModelActor
, all the pieces runs on the primary thread. I’ve learn on-line that it’s essential to instantiate it on a background thread, however it’s nonetheless executing strategies on the primary thread. I’ve additionally examine executors, however could not discover something working.
EDIT: It appears calling a MainActor
within the .activity {
introduces the problem?
This is my code to this point:
import SwiftUI
import SwiftData
@Mannequin
class Person {
var id: UUID
init(id: UUID) {
self.id = id
}
}
@MainActor
remaining class SomeMainActor {}
@foremost
struct MyApp: App {
var physique: some Scene {
WindowGroup {
ContentView()
.activity {
do {
let savedUserProvider = attempt await SavedUserProvider.createOnBackground()
let someMainActor = SomeMainActor()
await savedUserProvider.updateUser()
} catch {}
}
}
}
}
@ModelActor
actor SavedUserProvider {
static func createOnBackground() async throws -> SavedUserProvider {
await Job.indifferent(precedence: .background) {
let container: ModelContainer = {
let schema = Schema([
User.self
])
let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
return attempt ModelContainer(for: schema, configurations: [modelConfiguration])
} catch {
fatalError("Couldn't create ModelContainer: (error)")
}
}()
return SavedUserProvider(modelContainer: container)
}.worth
}
func updateUser() {
print()
// Runs on foremost thread
}
}
Has anybody managed to have SwiftData updates on a background thread with ModelActor ?