SwiftUI updating UIViewControllerRepresentable and/or manually binding to BindableObject

I've got a DocumentTextViewController that I want to use inside some swiftUI. I've created a UIViewControllerRepresentable wrapper as seen here:


// make this representable so it can be hosted in SwiftUI
struct DocumentTextView: UIViewControllerRepresentable {

    @ObjectBinding var textModel:TextModel
    @ObjectBinding var viewModel:DocumentViewModel // textview needs to know about this because it changes how it's rendered (performance)

    func makeUIViewController(context: UIViewControllerRepresentableContext<DocumentTextView>) -> DocumentTextViewController {
        return DocumentTextViewController(textModel: textModel, viewModel: viewModel)
    }

    func updateUIViewController(_ uiViewController: DocumentTextViewController, context: UIViewControllerRepresentableContext<DocumentTextView>) {
        uiViewController.viewModelUpdated(viewModel: uiViewController.viewModel)
    }
}

Unfortunatly this doesn't seem to be working. What I'd like to do is be able to create this in swiftUI using a line like: DocumentTextView(textModel: text, viewModel: viewModel), then have the viewController update it's internal view based on changes both to the textModel and the viewModel.


The code above seems to init several of the DocumentTextView structs when i've only added one of them to the SwiftUI content view. It creates the view controller properly, inits it with the correct properties and displays it propertly. Then when viewModel's didChange fires it doesn't properly call updateUIViewController.


As a work-around i've tried manually binding to the changes in the textModel like this:


        textSubscription = textModel.didChange
            .debounce(for: .milliseconds(2), scheduler: RunLoop.main)
            .receive(on: RunLoop.main)
            .sink(receiveValue: { self.textModelUpdated(textModel: $0) })


The above seems to work, but i have no idea if thats a proper way to watch for changes, and it doesn't seem to work properly on my viewModel property. only my textModel property. Possibly because fewer other views are binding to textModel in swiftUI.


Anyway, i have no idea if the above is the proper way to update a UIViewControllerRepresentable based on changes to it's underlying model. Is there any clear documentation on how to do it? The coordinator stuff seems more related to two way data flow, which i don't really need at this point.

SwiftUI updating UIViewControllerRepresentable and/or manually binding to BindableObject
 
 
Q