Swift Combine: What does objectWillChange do?
When developing with SwiftUI, you cannot help but use ObservableObject. But do you know exactly what ObservableObject does? ObservableObject basically updates SwiftUI’s view when data changes.
objectWillChange.send() forces your SwiftUI Views to redraw
What will happen in sink
{ } block?
Whenever you make your class conform to ObservableObject
, it gives objectWillChange
property. If you subscribe to objectWillChange
with sink()
, you can be notified when@Published text
‘s value changes
objectWillChange.sink is not showing you the latest value
For the example, I prepared a sample project. Whenever changeTextContent()
is called, it updates @Published text. But look at this code snippet.
What do you expect it to happen? Would it be the updated text?
Strange Result
From the code snippet above, you might have expected changed value
. But you are receiving the previous value? Why is that?
Because the
objectWillChange.send()
is called before setting the value!
As a result, when you receive value change event, its value is not updated yet!
Set up ObservableObject without @Published
To make you understand better, I prepared another example. Instead of using @Published
Property, I set up the value with Property Observer willSet
. This code snippet will give you the same result!
Conclusion
- ObservableObject gives you
objectWillChange
property. - You can access
objectWillChange
and subscribe. - objectWillChange is called before actually changing the value!