May I inquire about the differences between the two ways of view under the hood in SwiftUI?
class MyViewModel: ObservableObject {
@Published var state: Any
init(state: Any) {
self.state = state
}
}
struct MyView: View {
@StateObject var viewModel: MyViewModel
var body: some View {
// ...
}
}
struct CustomView: View {
let navigationPath: NavigationPath
@StateObject var viewModel: MyViewModel
var body: some View {
Button("Go to My View") {
navigationPath.append(makeMyView())
}
}
}
// Option 1: A viewModel is initialized outside view's initialization
func makeMyView(state: Any) -> some View {
let viewModel = MyViewModel(state: state)
MyView(viewModel: viewModel)
}
// Option 2: A viewModel is initialized inside view's initialization
func makeMyView(state: Any) -> some View {
MyView(viewModel: MyViewModel(state: state))
}
For option 1, the view model will be initialized whenever custom view is re-rendered by changes whereas the view model is only initialized once when the view is re-rendered for option 2.
So what happens here?