After years of working with RealmSwift, I’m trying to get my head around using Realm with SwiftUI. So far everything is going well except I have an issue whereby I can’t detect when an ObservedRealmObject
has been deleted.
My setup is fairly straightforward in that I have a list in a sidebar which is populated from an @ObservedResults and then later a ForEach loop:
@ObservedResults(Item.self) var items
var body: some View {
List(selection: $navigationModel.selectedItem) {
ForEach(items, id: \.self) { item in
NavigationLink(value: item) {
ItemRow(item: item)
}
}
.onDelete(perform: $items.remove)
}
}
I then have a detail view which uses an ObservedRealmObject
to display an item:
@ObservedRealmObject var item: Item
var body: some View {
Text(item.name)
}
If I change the name of the Item
within my sidebar, then the item is instantly updated in the detail view.
However, if I delete the Item
from the sidebar, there doesn’t seem to be a way to detect that within the detail view and thus navigate the user back. I assumed I’d be able to check if the object was invalidated (perhaps with an onChange
modifier) but the object insists it is still valid even after deletion. I can also read the properties (i.e. checking item.name
on a button press) without any crashes. If I try to unthaw the item, then it returns nil and I can go back but it doesn’t seem optimal to have to unthaw the item on every render to check if it still exists.
Am I missing something obvious? I’m sure there must be a way for SwiftUI to be notified when an ObservedRealmObject has been deleted…