Photo by Daniel Lerman on Unsplash

Define a Subscription Mechanism in order to Notify Multiple Objects

Swift ā€” Problems Catalogue #13

Alex Ilovan
Published in
3 min readSep 13, 2022

--

Problem Definition:

Consider the following scenario. You have to implement a bird watching app šŸ¦¤ how lovely. This app needs to scan birds when they appear (the key word is when) and notify subscribed enthusiasts.

In a nutshell we need an event based system that can transmit information from one entity to multiple entities at the same time.

Problem Solution:

Solution ā€”Observer itā€™s a behavioral design pattern that allows you to create a subscription mechanism in order to notify multiple objects at the same time.

Real-World Usage:

First, as always, we start with a protocol āœØ that has a notify method. With this method the entity that receives information will receive the notification and do something with it.

Next, letā€™s create two types of enthusiasts, a duck one šŸ¦† and a stork onešŸ¦© (yup, thatā€™s a flamingo emoji) and conform them to the Observer protocol. Implementing the notify(scanner: BirdScanner) we can verify the notificationā€™s observedBird state and based on it we can do some business logic.

Figure 1. Observers

Now, letā€™s handle the entity that ā€œsendsā€ information. Technically it sends itself.

The BirdScanner has an array of observers and if the notify() method is called it goes through them and calls every observerā€™s notify method and passes itself and exposing the observedBird variable.

When talking about the observer design pattern, the BirdScanner class is called usually a Subject.

Also, we need two additional important methods, the subscribe and the unsubscribe method that adds and removes observers from our array.

Figure 2. Subject

Finally, letā€™s put everything together in our BirdWatchingApp and use our subscription mechanism to itā€™s fullest.

Figure 3. Bird Watching App

From this point on, the sky is the limit šŸš€ wellā€¦almost.

Of course, this design pattern has its limitations but used in moderation, itā€™s a great tool in our development toolbox.

This is the next article in the Swift Problems Catalogue series in which Iā€™ll tackle general software development problems. The aim is to have a quick reference guide that can be easily accessed when having a design/algorithm dillemma.

Let me know what you think and donā€™t be shy to share where and when this pattern simplified your coding experience šŸŽ¶

--

--

Alex Ilovan
salt&pepper

šŸš€Head of Mobile Development @S&P šŸ’»Comp. Engineer šŸŖEngineering Manager. You can visit at: https://www.linkedin.com/in/alex-ilovan-129161b4/