'SwiftUI pass Binding by ref to a child ViewModel

In SwiftUI, I am trying to create some binding between a parent ViewModel and a child ViewModel, here is a simplified example of my scenario:

The parent component:

class ParentViewModel : ObservableObject {
    @Published var name = "John Doe"

    func updateName() {
        self.name = "Jonnie Deer"
    }
}

struct ParentView: View {
    @StateObject var viewModel = ParentViewModel()

    var body: some View {
        VStack {
            Text(viewModel.name)
            ChildView(name: $viewModel.name)
            // tapping the button the text on parent view is updated but not in child view
            Button("Update", action: viewModel.updateName)
        }
    }
}

The child component:

class ChildViewModel : ObservableObject {
    var name: Binding<String>
    
    var displayName: String {
        get {
            return "Hello " + name.wrappedValue
        }
    }
    
    init(name: Binding<String>) {
        self.name = name
    }
}

struct ChildView: View {
    @StateObject var viewModel: ChildViewModel

    var body: some View {
        Text(viewModel.displayName)
    }
    
    init(name: Binding<String>) {
        _viewModel = StateObject(wrappedValue: ChildViewModel(name: name))
    }
}

So, as stated in the comments, when I tap the button on the parent component the name is not getting updated in ChildView, as if the binding is lost... Is there any other way to update view model with the updated value? say something like getDerivedStateFromProps in React (becuase when tapping the button the ChildView::init method is called with the new name.

Thanks.



Solution 1:[1]

Apple is very big on the concept of a Single Source of Truth(SSoT), and keeping it in mind will keep you from getting into the weeds in code like this. The problem you are having is that while you are using a Binding to instantiate the child view, you are turning around and using it as a @StateObject. When you do that, you are breaking the connection as @StateObject is supposed to sit at the top of the SSoT hierarchy. It designates your SSoT. Otherwise, you have two SSoTs, so you can only update one. The view model in ChildView should be an @ObservedObject so that it connects back up the hierarchy. Also, you can directly instantiate the ChildViewModel when you call ChildView. The initializer just serves to decouple things. Your views would look like this:

struct ParentView: View {
    @StateObject var viewModel = ParentViewModel()

    var body: some View {
        VStack {
            Text(viewModel.name)
            // You can directly use the ChildViewModel to instantiate the ChildView
            ChildView(viewModel: ChildViewModel(name: $viewModel.name))
            Button("Update", action: viewModel.updateName)
        }
    }
}

struct ChildView: View {
    // Make this an @ObservedObject not a @StateObject
    @ObservedObject var viewModel: ChildViewModel

    var body: some View {
        Text(viewModel.displayName)
    }
}

Neither view model is changed.

Solution 2:[2]

Get rid of the view model objects and do @State var name = “John” in ParentView and @Binding var name: String in ChildView. And pass $name into ChildView’s init which gives you write access as if ParentView was a view model object.

By using @State and @Binding you get the reference type semantics you want inside a value type which is the power of SwiftUI. If you just use objects you lose that benefit and have more work to do.

We usually only use ObservableObject for model data but we can also use it for loaders/fetchers where we want to tie some controller behaviour to the view lifecycle but for data transient to a view we always use @State and @Binding. You can extract related vars into their own struct and use mutating funcs for other logic and thus have a single @State struct used by body instead of multiple. This way it can still be testable like a view model object in UIKit would be.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yrb
Solution 2