I have a banner component written in SwiftUI that I am embedding in a ViewController using a UIHostingController.view
as a return type in a method:
public static func createBannerView(thing: String) -> UIView? {
let viewModel = bannerViewModel(dependency: SomeRepository(thing: thing))
return UIHostingController(rootView: bannerView(viewModel: viewModel)).view
}
//I do check for nil, but shortened for readability...
infoBanner.addSubview(createBannerView())
NSLayoutConstraint.activate([...
Inside the view, I am referencing the ViewModel as an @ObservedObject
.
I have heard concerns that I should be referencing the ViewModel as a @StateObject
instead, because the ViewModel is being created outside of the ViewController. I understand this concern in a situation where the parent view and child view are SwiftUI views, because changes to the immutable parent view will recreate the child view and without the @StateObject
declaration the data in the @ObservableObject
will be lost.
But in this situation, the parent UIKit powered ViewController is not immutable, and can change all it wants without forcing a redraw of the child SwiftUI view.
My questions:
1: Is there a benefit in this situation to marking the ViewModel as a @StateObject
or @ObservedObject
2: Is there a danger to marking the ViewModel as a @StateObject
or @ObservedObject
UPDATE
An answer on another thread gives a great explanation of how these two objects differ: @StateObject vs @ObservedObject when passed externally but owned by the view