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

Next
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.

Transcript: 17. Observable Objects

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.