Publishing changes to a collection of observable objects

Viewed 334

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()
    }
}
3 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.

Problem with your approach is that TextHolder is a class, which is reference type, if you change any value in it, changes won't reflect to array that's why SwiftUI view is not updated.

Approach 1:

You can change TextHolder from class to struct, if you change any value in struct a new copy is created, your array will get the change to as your SwiftUI view.

Please try below code

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

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

struct TextHolder {
    var text: String = ""
    
    mutating func toggle() {
        text = UUID().uuidString
    }
}

Approach 2:

After changing value you have to manually tell your viewModel that something is changed, please refresh.

Button("Toggle") {
     vm.texts[0].toggle()
     vm.objectWillChange.send()
}

Hope it will help you to understand.

If you are not able to convert the class to a struct, an approach you can take is to subscribe to all objectWillChange publishers of the items in the array, and emit one for the main model, when one of those objects change:

@Published var texts: [TextHolder] = [.init(), .init()] {
    didSet {
        updateTextsSubscriptions()
    }
}

private var textsSubscriptions = [AnyCancellable]()

private func updateTextsSubscriptions() {
    textsSubscriptions = texts.map {
        $0.objectWillChange.sink(receiveValue: {
            self.objectWillChange.send()
        })
    }
}

You will also need to call updateTextsSubscriptions from within the initializer(s), to make sure any initial values for the texts array are monitored:

init() {
    updateTextsSubscriptions()
}
Related