Your Second iOS & SwiftUI App

Nov 4 2021 · Swift 5.5, iOS 15, Xcode 13

Part 2: Data Flow

17. Observable Objects

Episode complete

Play next episode

About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 16. Model Objects Next episode: 18. Challenge: Micro-Review

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You've reached locked video content where the transcript will be shown as obfuscated text.

All right. We did all of that work, transforming our book type. So let's see if our bookmark button is working in a live preview yet. Select a book and click on the bookmark. Well, it doesn't look like it's working here. But if I go back to my library and then to the book again, the bookmark is empty now. So it's sort of working. What's going on here? What's happening is that although the button is doing its job, the DetailView doesn't know that it needs to update. To solve that you'll be making a little use of Apple's Combined Framework. Now plumbing the depths of Combined is not something appropriate to do when you're just writing your second app. We've got video content and a book on Combine, which I hope you'll check out in the future. But it's a little bit more advanced than this course. Fortunately, for us, one of the things that's very easy to do with Combine is to take an object observe changes to its properties and react to those changes in SwiftUI. The first step in the process is to import Combine in Book.swift. Within Combine, there's an attribute you'll want to apply to your variables. It's named Published. I think it's a pretty good name. The idea is, when you're published variables change, anything that subscribes to be notified of those changes will be. But book is a reference type now. So even when it's variables change, the book instance itself is not considered to have changed. In order to tie the ideas together, you adopt Combine's ObservableObject protocol. Now our book will listen for changes to its published variables. And when that happens, anything observing the book can respond. So what we need to do is ask our DetailView to observe it's book property. SwiftUI has a property wrapper for that, ObservedObject. And now we don't even need to go to ContentView to test this out. We can live preview it right here. Let me click on the bookmark button. We can see the book changes published right here.