Passing ObservedRealmObject between views in SwiftUI

Hi there!

I am a bit confused about passing @ObservedRealmObject to children views in SwiftUI. Unlike with @StateObject where I inject it as EnvironmentObject, I need to pass @ObservedRealmObject as argument. Would this example be the proper way to do this?

struct ContentView: View {
    @ObservedRealmObject var someObject: SomeObject
    var body: some View {
        ...
        SubView(someObject: someObject)
        ...
    }
}

struct SubView: View {
    @ObservedRealmObject var someObject: SomeObject
    var body: some View {
        ...
    }
}

While this seems to work, I think I am concerned as this looks like I have created two sources of truth. I also tried removing the property wrapper in SubView but I end up with stale data when modifying the object.

What is the correct approach here? Thanks!

When using @ObservedRealmObject, it is correct to pass it as an argument to child views, as shown in your example.

Having multiple references to the same @ObservedRealmObject instance in different views does not create multiple sources of truth, as the object is still managed by the Realm database and its changes are reflected in all references to it. However, passing the @ObservedRealmObject instance as an argument ensures that the child views have the latest version of the object.

In your example, removing the property wrapper in the SubView would result in stale data because @ObservedRealmObject is responsible for monitoring changes to the object and updating the view accordingly. Without it, the view would not receive updates when the object changes in the Realm database.

So, in conclusion, the approach you’ve shown is the correct way to pass the @ObservedRealmObject instance to child views.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.