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?

objectWillChange

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

Sample App
TextField and Button

For the example, I prepared a sample project. Whenever changeTextContent() is called, it updates @Published text. But look at this code snippet.

What would viewModel.text print?

What do you expect it to happen? Would it be the updated text?

What would happen?

Strange Result

This prints out the previous value.
Instead of “value changed to Hello World”, it’s just “Click to change value”!

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

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

  1. ObservableObject gives you objectWillChange property.
  2. You can access objectWillChange and subscribe.
  3. objectWillChange is called before actually changing the value!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!