What is the idiomatic way to use a ModelContext
in a document based SwiftData app from a background thread?
The relevant DocumentGroup
initializers do not give us direct access to a ModelContainer
, only to a ModelContext
.
Is it safe to take its modelContext.container
and pass it around (for creating a ModelContext on it on a background thread) or to construct a ModelActor
with it? Is it safe to e.g. put a ModelActor so created into the environment of the root view of the window and execute various async data operations on it in Tasks throughout the app, as long as these are dispatched from within the window whose root view's ModelContext
was used for getting the ModelContainer
?
Is it safe to take its modelContext.container and pass it around (for creating a ModelContext on it on a background thread) or to construct a ModelActor with it?
Yes, ModelContainer
is Sendable
and is safe to be passed across actors.
Is it safe to e.g. put a ModelActor so created into the environment of the root view of the window and execute various async data operations on it in Tasks throughout the app, as long as these are dispatched from within the window whose root view's ModelContext was used for getting the ModelContainer?
By reading the above description, I am not quite clear how you would use ModelActor
, but since you have the model container (ModelContext.container), as mentioned above, you can create a model actor and use it to run a task in the following way:
let actor = MyTestModelActor(modelContainer: modelContainer)
try await actor.doSomething()
Best,
——
Ziqiao Chen
Worldwide Developer Relations.