Integrate Combine Into an App

Aug 5 2021 · Swift 5.4, macOS 11.3, Xcode 12.5

Part 1: Define a View Model

05. Use @ObservedObject to Monitor State

Episode complete

Play next episode

Next
About this episode
Leave a rating/review
See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 04. Use Publishers in the ViewModel Next episode: Part 1 Quiz: Integrate Combine into an App

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.

There's one more thing you'll do to the model before moving on, make it conform to ObservableObject, so that it can be observed throughout the app. What exactly does this do? For types that adopt ObserverbleObject, the compiler will automatically synthesize and object will change property, which is a publisher. And this gets called before the object changes. So any subscriber can be made aware. Adoption of this protocol also allows the object to used inside views. This along with the @Published properties we discussed in an earlier episode, helped tell the view when to refresh. Speaking of which, we know publishers don't exist in isolation, they need to have subscribers to start the flow of data. Luckily, there's a corresponding property wrapper in SwiftUI when working with models that adopt ObservableObject, and that's @ObservedObject. When this pairing occurs in your code, a binding is established between your view and the external model, unlike with @State where bindings happen within views. At that point, the steps are very familiar. When the external model changes, and the @Published properties publish their new values, the views that have that model decorated with an observed object, will receive that change and update their body properties. Let's take a quick look at the code needed for this change. In the JokesViewModel.swift file make JokesViewModel adopt ObservableObject. Now over in views, JokeCardView.swift decorate the viewModel with the @ObservedObject property wrapper. Views JokeView.swift also has a viewModel. So add the @ObservedObject property wrapper here as well. Great, our publishers are built and now hooked into our viewModel. Now we move on to our next feature. Storing like jokes in a Core Data database, which we'll do next.