Leave a rating/review
Alright, we did all that work transforming our Book type, let’s see if our bookmark button is working in a live preview!
Select a book, and click on the bookmark… Well, it doesn’t look like it’s working… But if I go back to My Library, and then, to the book again, it’s 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 detail view doesn’t know that it needs to update. To solve that, you’ll be making a little use of Apple’s Combine framework.
Now, plumbing the depths of Combine is not something appropriate to do when you’re just writing your second app.
We’ve got raywenderlich.com video content, and a book, on Combine – which I hope you check out in the future. But, it’s all a 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.
/// THE SOFTWARE.
import Combine
class Book {
Within Combine, there’s an attribute you’ll want to apply to your variables. It’s named “Published”.
@Published var microReview: String
@Published var readMe: Bool
I think it’s a pretty good name. The idea is, when your published variables change, anything that subscribes to be notified of such a change, will be.
But Book is a reference type now. So even when its 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.
class Book: ObservableObject {
Now, a 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 Detail View to Observe its book property.
SwiftUI has a property wrapper for that: “Observed Object”.
@ObservedObject var book: Book
And now, we don’t even need to go to ContentView to test this out.
When we click on the bookmark button, we can see the book changes published, right here.