Chapter 6. Observing Objects

Hi I am wondering why this chapter is using the old @ObservableObject with @Published instead of the new @Observable? Is there going to be an updated version of the book that uses the new syntax?

hi Jason! In section 3, I need to show how the main thread checker stops you from updating the UI from a background thread. @Observable doesn’t trigger the main thread checker.

I looked at section 3 and found the area with the purple warning on the UI not being updated on the main thread. That makes sense and I am glad it is intentional in the book. I always wonder what tech to use as things change and it seems like most of the internet is gravitating towards doing away with the @ObservableObject style. I guess I will wait a bit.

I am wondering then if this is a bug in Swift/Apple for the @Observable ? I would think this should work the same and trigger the warning as well. Thoughts?

Once you get into the habit of running UI updates on Main, feel free to use @Observable. If its current behavior is a bug, I expect Apple will fix it eventually. I think most developers haven’t even noticed this “bug”, as they all dispatch to Main automatically.

I came across it when I was trying to persuade a bootcamp cohort that they shouldn’t mark all their @Observables as MainActor. My argument was that the compiler wouldn’t tell them when they were running a slow task on Main, but the main thread checker would alert them to any attempts to update UI on a background thread. To my surprise, “demonstrating” this with @Observable didn’t work!

1 Like

Thanks for expanding on that! I think eventually I am going to try to get to @Observable after I finish this book and see how it goes. I may try to convert some of these to that and then make sure I get through the Swift Concurrency book to understand it more.

1 Like