Using a wrapper allows us to pass EnvironmentObject down into ObservedObject. Nice approach..
But what if you want to manipulate the userData inside ViewObject without an entirely new ViewObject being created every time?
In my app entire view is recreated after I change EnvironmentObject and i don't know how to avoid this.
struct MyCoolView: View {
@EnvironmentObject var userData: UserData
var body: some View {
MyCoolInternalView(ViewObject(id: self.userData.UID))
}
}
struct MyCoolInternalView: View {
@EnvironmentObject var userData: UserData
@ObservedObject var viewObject: ViewObject
init(_ viewObject: ViewObject) {
self.viewObject = viewObject
}
var body: some View {
Text("\(self.viewObject.myCoolProperty)")
}
}
Here is a demo of possible solution - make viewObject as
StateObject
(this will make it persistent through view refresh) and injectuserData
into itTested with Xcode 12.1 / iOS 14.1