I have a simple example. I fetch all Trip
objects from my database:
import SwiftData
@Model
class Trip {
var name: String
}
func fetch() {
let container = ModelContainer(for: Trip.self)
let context = ModelContext(container)
let fetchDescriptor = FetchDescriptor<Trip>()
let trips = try! context.fetch(fetchDescriptor)
// Store it somewhere ...
}
How do I observe changes to the trips array? I know that the individual objects inside the array are observable and will change when something is committed to the database. However, what if the order changes, or some trip is deleted or new ones are inserted? I cannot find a mechanism to get notified of this.
The only way I found was using the new @Query
property wrapper in SwiftUI. But I want to observe changes outside the SwiftUI environment, in separate classes. Is there a way to do this?
DidSave notification seems to be working, for basic save observation. (stated in comments by hayesk)
Conversion to stream worked for me as well.
NotificationCenter.default.addObserver(
forName: ModelContext.didSave,
object: nil,
queue: .main
) { _ in
...
}
or
let stream = AsyncStream {
NotificationCenter.default.notifications(named: ModelContext.didSave)
}
for await _ in stream {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With