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
?