0

I'm trying to better understand the mechanism how SwiftUI gets notified about changes in observed data and invalidates UI.

In particular, I wonder if something won't work correctly (e.g. animations?) when objectWillChange.send() is called on ObservableObject after the underlying data model have changed, and more importantly why is that.

If it doesn't matter when the synthesized publisher notifies its observers after the change, then why is it named objectWillChange and not objectDidChange?

Let's say I have a view model like this the following and it observes changes in some model via a delegate method (the code is simplified for the example purposes):


protocol ModelDelegate: AnyObject {
    func modelDidChange() {
}

class Model {

  weak var delegate: ModelDelegate?

  var stroredString: String {
    didSet { self.delegate?.modelDidChange() }
  }

}

class ViewModel: ObservableObject {

  private let model: Model = Model(delegate: self)

  var calculatedProperty: String { model.storedString }

}

extension ViewModel: ModelDelegate {

  func modelDidChange() {
    // we get called when the change has already happened.
    // is it wrong to publish the change via objectWillChange?
    self.objectWillChange.send()
  }
}

And then the View looks like this:

struct MyView: View {

  @ObservedObject private var viewModel: ViewModel

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

Question

Can I expect that something's not going to work correctly when objectWillChange.send() is called on ObservableObject after the underlying data model have changed? If yes, in which case and more importantly, why is that?

If it doesn't matter when the synthesized publisher notifies its observers after the change, then why is it named objectWillChange and not objectDidChange?

Tom Kraina
  • 3,569
  • 1
  • 38
  • 58
  • 1
    You shouldn't expect any issues, there is no reason to think there would be issues. – lorem ipsum Dec 08 '22 at 14:31
  • 1
    It is named `objectWillChange` simply because the `Published` protocol triggers from the [`willSet` block](https://developer.apple.com/documentation/combine/published). For an exhaustive discussion, see [this question and its answers](https://stackoverflow.com/questions/59519530/how-does-combine-know-an-observableobject-actually-changed/61675243#61675243) – Yrb Dec 09 '22 at 17:01

0 Answers0