Skip to content

How to Use @Published in an ObservableObject using Swift

Swift, ObservableObject, Combine1 min read

In Swift, @Published is a property wrapper that enables the automatic generation of a publisher for a property. By using @Published in an ObservableObject, changes to the property can be observed and reactively updated by subscribers.

An ObservableObject is a protocol that defines a type that can be observed for changes. When an object that conforms to the ObservableObject protocol has a property marked with @Published, changes to that property will automatically trigger the object to notify its subscribers. The subscribers can then react to these changes by updating their user interface or performing some other action.

Here is an example of how to use @Published in an ObservableObject:

1import Combine
3class MyObservableObject: ObservableObject {
4 @Published var myProperty: String = "Hello, world!"

In this example, MyObservableObject is a class that conforms to the ObservableObject protocol. The class has a property called myProperty that is marked with @Published. The type of myProperty is String and it has a default value of "Hello, world!".

Now, let's create a subscriber that can observe changes to myProperty:

1let myObject = MyObservableObject()
3let cancellable = myObject.$myProperty
4 .sink { value in
5 print("myProperty changed to \(value)")
6 }
8myObject.myProperty = "Goodbye, world!"

In this example, we create an instance of MyObservableObject and assign it to myObject. We then create a subscriber by calling the $myProperty property on myObject. The $myProperty property is automatically generated by @Published and returns a publisher that can be used to observe changes to myProperty.

We call the sink method on the publisher to create the subscriber. The sink method takes a closure that will be called each time the value of myProperty changes. In this case, we print a message that shows the new value of myProperty.

We then update the value of myProperty to "Goodbye, world!" and the subscriber is automatically notified of the change.

Finally, we call the cancel method on the cancellable object to stop the subscription.

Using @Published in an ObservableObject is a powerful way to create reactive user interfaces in Swift. By marking properties with @Published, changes to those properties can be automatically observed and reacted to by subscribers. This can help make your code more concise and easier to understand.