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