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 ObservableObject, the compiler will automatically synthesize an objectWillChange 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 be used inside views.
This, along with the @Published properties we discussed in an earlier episode, help 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 the flow of data. Luckily there is a corresponding property wrapper in SwiftUI when working with models that adopt ObservableObject - @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 @ObservedObject 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
public final class JokesViewModel: ObservableObject {
Now, over in Views/JokeCardView.swift, decorate the viewModel with the @ObservedObject property wrapper
@ObservedObject var viewModel: JokesViewModel
Views/JokeView.swift also has a viewModel, so add the @ObservedObject property wrapper here as well
@ObservedObject private var viewModel = JokesViewModel()
Great - our publishers are built and are now hooked into our view model. Now to move onto our next feature - storing liked jokes in a Core Data database, which we’ll do next.