nakajima / LiveModelDemo

1 stars 0 forks source link

Usage with @State? #1

Closed bastiaanterhorst closed 1 month ago

bastiaanterhorst commented 1 month ago

Hi, I came here looking for a way to use background processing with SwiftData while keeping my @Query's updating as well. @LiveModel looks like a great solution, however I can only get it to work with views that take a SwiftData model as a regular var. Like in your example: @LiveModel var person: Person

I'd like to use SwiftUIs @State as well, but including both gives me an error:

@LiveModel @State var todo: Todo
Generic class 'LiveModel' requires that 'State<Todo>' (aka 'State<TodoSchemaV1.Todo>') conform to 'PersistentModel'

Any ideas to get this to work?

nakajima commented 1 month ago

Hey, sorry I missed this earlier! Curious why you need the todo to be marked as @State? I'd think that having @LiveModel would be enough to keep things observable and let the view react accordingly?

bastiaanterhorst commented 1 month ago

Hey Pat, thanks for your response!

The reason that I'd like to use @State is to allow turning the variable into a binding, so I can put it into a TextField or similar and have it automatically update the underlying data:

TextField("Title", text: $todo.title)

The use case I have is that I have a view that displays data and allows for modification of that data. At the same time, that data might be modified by a background thread as well (hence the use of @LiveModel).

Or is this not how you would approach things?

nakajima commented 1 month ago

I think the problem with treating todo as both @State and also a SwiftData object is that @State says "this object's state is owned by this view" whereas the @LiveModel says "this object's state is owned by the DB".

I think I'd maybe just have a view model object for that view that gets the data from the todo as state in that view. Then you could also have the @LiveModel object in there and listen for updates to update your view model accordingly?

bastiaanterhorst commented 1 month ago

I get what you're saying, but that is how it works with @Query. What you get back is a list of objects who's state is owned by the DB but also modifiable by the view through bindings.

Your suggestion with a view model is a neat solution though; I'll look into that!