Swift Combine: Understanding Publisher-Subscriber Pattern in 2 seconds

KD Knowledge Diet
4 min readSep 24, 2022

Publisher Subscriber relationship is an incredibly easy concept. However, it is difficult to understand what they mean because some writes about it with the mind of a scholar. As long as you know this concept, you don’t need to learn anything new to use rxdart, rxswift, combine, or rxjava. It feels all natural to you. Let’s begin

Reactive Programming

If you are an iOS developer, you probably handled asynchronous task with closure and delegate pattern. So did I. But closure can lead you to callback hell. delegate pattern misused can lead you to write a super-hard-to-understand complex code. Reactive Programming has come to the rescue. The whole purpose of Combine Framework or Reactive Programming is to achieve this.

  • Customize handling of asynchronous events by combining event-processing operators.

So basically, you can replace closure and delegate pattern!

The base of Reactive Framework or Combine framework

Publisher -> Subscriber

At the core level, you have a publisher and a subscriber. A subscriber can subscribe to a publisher. Then when Subscriber is subscribed, then the publisher can emit those stream of data events. Subscriber receives those data stream of data events.

Netflix Analogy

This can be anything or any kind of data. You can think of it if you are Subscriber and you subscribes to Netflix, then Netflix will be your publisher and then Netflix will be sending you some data, which in this case will be new movies.

So, any time a new movie is added, you get that particular subscription, the data, whether you’re interested in action movies or fiction movies or comedy movies

Depending on your subscription, you will get that particular data and you can consider that data as a stream of data.

Understanding Publisher — Subscriber Model

In oder to understand the publisher and subscriber model, let’s go ahead and jump into code and look at how you used to do things previously using notification center.

Notification center users a similar kind of a pattern, not exactly the same publisher and subscriber pattern, but a similar kind of a pattern where it helps you understand what publishers and subscribers are in code.

// Define Event 
let notification = Notification.Name("MyEvent")
// Notification Center
let center = NotificationCenter.default
// Receive Event
let observer = center.addObserver(forName: notification, object: nil, queue: nil) { notification in
print("Notification Received") // This will be fired
}
// Post Event or 'Emit' Event
center.post(notification, object: nil)

Basically, I created an event and get NotificationCenter and stored in a new variable. I also created observer to receive event and finally posted an event.

When you execute the code above, you will see Notification Received printed out.

Keep in mind that this is not the reactive way of programming, this is the imperative programming.

But the important part is that it fires the notification and you can actually see it being displayed in the console or in the output window.

Whenever you post an event with center.post(), observer will be triggered. This is somewhat similar to Combine’s Publisher-Subscriber. But not exactly. Because the whole purpose of using Swift Combine Framework is to achieve “Customize handling of asynchronous events by combining event-processing operators.” In other words, Reactive Programming.

So how do you then use combine framework to make it reactive?

Sending Notifications using Publisher and Subscriber

Now let’s learn how you can use the publisher-subscriber model to create the same exact situation where a notification center can post a subscription and then you can subscribe.

// Create an event
let notification = Notification.Name("MyNotification")
// Publihser ios 13++
let publisher = NotificationCenter.default.publisher(for: notification, object: nil)
// Subscribe
publisher.sink { _ in
print("Notification Received")
}
// Post Event
NotificationCenter.default.post(name: notification, object: nil)

First, I created an event with [Notification.Name](<http://Notification.Name>) and then created NotificationCenter.default.publisher and saved it on a new variable. Now, whenever I post an event with NotificationCenter.default.post(), the subscriber will receive the data.

The Main Difference for Combine Approach

Whole bunch of methods available for combine frameworks

Before you finally get the result from publisher, you can attach any operator you want!

Conclusion

  • At the core level of Combine Framework , there’s Publisher-Subscriber Pattern.
  • When you subscribe to a publisher, you can receive event emitted by the publisher.
  • Before you subscribe, you can add operators to handle the stream of data.
  • The whole purpose of reactive programming is “Customize handling of asynchronous events by combining event-processing operators.

--

--

KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!