Skip to content

Instantly share code, notes, and snippets.

@ikyhtr
Last active September 4, 2022 06:16
Show Gist options
  • Save ikyhtr/1cfe35cdc0a44e2d7bf2204ce2f7b58a to your computer and use it in GitHub Desktop.
Save ikyhtr/1cfe35cdc0a44e2d7bf2204ce2f7b58a to your computer and use it in GitHub Desktop.

ObservableObject

A type of object with a publisher that emits before the object has changed. https://developer.apple.com/documentation/combine/observableobject

This protocol lets you sync any views referring to a property of a class conformed to it.

@ObservedObject

Well, we have a class declared as below:

class MovieModel: ObservableObject {
    @Published var title: String
    @Published var love: Bool = false
    
    init(_ title: String) {
        self.title = title
    }
}

Then, we declared a property with @ObservedObject attribute in your view file. Naturaly this will holds an instance of the type.

struct Movie: View {
    @ObservedObject var movie: MovieModel
    
    var body: some View {
        VStack {
            HStack {
                Text(movie.title)
                    .font(.title)
                Label(
                    "Toggle",
                    systemImage: movie.loved ? "heart.fill" : "heart"
                )
                    .labelStyle(.iconOnly)
                    .foregroundColor(movie.loved ? .pink : .gray)
            }
            Toggle(isOn: $movie.loved) {
                Text("Love it")
            }
        }
        .padding(10)
    }
}

The @Published attribute is a property wrapper that lets you access a Publisher type using the $. Instances with @Published of a class must conform to ObservableObject.

Changes to all properties declared using @ObservedObject in the view are observable. The view having the instance will are immediately re-rendered if it has changed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment