Observer Pattern

Aymen Afia
3 min readDec 24, 2020

--

The observer pattern lets one object observe changes on another object. Apple added language-level support for this pattern in Swift 5.1 with the addition of Publisher in the Combine framework.

This is a behavior pattern, it focused to observe changes on other object.

This pattern involves three types:

  1. The subscriber is the “observer” object and receives updates.
  2. The publisher is the “observable” object and sends updates.
  3. The value is the underlying object that’s changed.

When should you use it?

Use the observer pattern whenever you want to receive changes made on another object.

This pattern allows the model to communicate changes back to the view controller without needing to know anything about the view controller’s type. Thereby, different view controllers can use and observe changes on the same model type.

Combine makes this pattern to be easier to implement.

  • First of all we need to import our Combine framework, otherwise we are not going to be able to use @Published.
  • Next we are basically creating a Person class that receives a nickname.
  • We must not forget to declare our nickname property as @Published

Warning ⚠️ To use @Published our variable cannot be a constant, also it can just be used with classes not with structs.

@Published has created 2 of the objects that conform this pattern for us, the Publisher and the Stored Value, so we just need to take care about the Subscriber

We have created a new instance of our class that contains our Observable property

we declare our publisher property with our nickname property from our Person class

So, what publisher property exactly is 🤷‍♂️? — We know that nickname was declared as a String, so if you think that publisher is a String, well you are almost correct, using $ before our property, turns our value type to Published<String>.Publisher

so lets create our subscriber.

let's dive in sink method, that method attaches a subscriber with closure-based behavior, so each time our publisher changes, that in this case is our $nickname property of Person, the closure in our subscriber will print our new change.

Finished !!!! 😁, of course this is just a useful approach to use Combine the huge framework.

--

--