Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Publishing changes to a collection of observable objects

I have an issue with propagating changes that happen to objects in the view model that are kept in an array.

I understand that @Published for a collection would work if the collection itself changes (eg. if elements were struct not class). Assuming that I need to preserve classes as classes. Is there a way to propagate events to a view, so that it knows it should be refreshed.

I have been trying all nasty ways like implementing ObservableCollection or ObservableArray but nothing seems to work.

Below an example of what I am struggling with. Toggle is changing internally element of an array which has all the ObservableObject conformance and @Published annotation but still Text is not being refreshed.

import SwiftUI
import Combine

struct ContentView: View {
    @StateObject var vm = ViewModel()
    
    var body: some View {
        Text(vm.texts.first!.text)
            .padding()
        
        Button("Toggle") {
            vm.texts.first?.toggle()
        }
    }
}

class ViewModel: ObservableObject {
    @Published var texts: [TextHolder] = [.init(), .init()]
}

class TextHolder: ObservableObject {
    @Published var text: String = ""
    
    func toggle() {
        text = UUID().uuidString
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
like image 280
Fishman Avatar asked Oct 16 '25 11:10

Fishman


1 Answers

Note: this is based on the requirement you listed of "Assuming that I need to preserve classes as classes" -- otherwise, making your model a struct gives you all of this behavior for free.

You can call objectWillChange.send() manually on the ObservableObject. For example:

Button("Toggle") {
    vm.texts.first?.toggle()
    vm.objectWillChange.send()
}

Major downsides include having to add code to call this at each mutation site and actually remembering to do this. You could do things to compartmentalize the code a little more like moving toggle to the parent object and passing an index to it -- then, you could keep all of the objectWillChange calls in the parent. Also, you could experiment with KVO to watch the properties of the child objects and call objectWillChange when you see one of them change.

like image 194
jnpdx Avatar answered Oct 19 '25 07:10

jnpdx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!