Still wondering about objectWillChange (vs objectDidChange) magic :)

Hi all,

The WWDC video offers (at about 16:45) as short explanation as to why it's "objectWillChange" instead of "objectDidChange". He said it's because SwiftUI needs to coalesce the changes.

Okay, but then how does it know when the changes have ended?

It seems like you'd need two events. Something like:

Code Block swift
self.objectWillChange.send()
self.foo = ...
self.bar = ...
self.objectHasFinishedChanging.send()

or

Code Block swift
self.objectChanges {
self.foo = ...
self.bar = ...
}


My assumption is it works similar to UIView’s/NSView’s setNeedsDisplay() (docs):


The view is not actually redrawn until the next drawing cycle, at which point all invalidated views are updated.

So objectWillChange schedules an update, which occurs in SwiftUI’s equivalent of the next drawing cycle.
Yeah, but then that doesn't explain why they changed it from objectDidChange to objectWillChange. The former would also work perfectly fine if it was merely a way to say "update on next cycle".
According to the “Manually publishing ObservableObject changes” post on the Hacking with Swift website (I can’t link it here due to forum restrictions):

As its name implies, this publisher should be triggered immediately before we make our change, which allows SwiftUI to examine the state of our UI and prepare for animation changes.

That makes sense to me. SwiftUI might need to know the old value in some cases in order to perform animations.
More precisely, from a SwiftUI engineer (twitter.com/luka_bernardi/status/1151633281982406656):
> We made the change because it allows us to do a better job in coalescing updates; especially in the presence of animations.
Still wondering about objectWillChange (vs objectDidChange) magic :)
 
 
Q