Better Programming

Advice for programmers.

Follow publication

Member-only story

Build Event Listeners in Swift

Alcivanio (Swift)
Better Programming
Published in
4 min readFeb 20, 2020

--

Photo by Lee Campbell on Unsplash.

Today, we will talk about how to create an implementation based on event listeners. This implementation will be retain-cycle-free. I will also give a brief description of how event listeners work and why we have to care about retain cycles when implementing them.

Overview of Event Listeners

Sometimes, you want to notify one or more objects that an event has occurred. For example, it could be the fact that the user has logged out or logged into the app. This kind of thing can be easily done by using delegates. One object implements a protocol and becomes a "listener" of the user auth state. But what happens when more than one object wants to listen to the user auth state? A single delegate is not enough anymore.

Whenever we want to spread the information that an event has happened to everyone, we can use a few types of approaches. One of them is notifications. NSNotifications works like a broadcast that will notify all the classes about your event, and you may only have to implement a function to receive that notification. The problem with them is that the OS notifies basically all of the classes alive about your event. Sometimes, we don't want that because it’s extra effort that's not being…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

--

--

Alcivanio (Swift)
Alcivanio (Swift)

Written by Alcivanio (Swift)

Computer Engineer + iOS Engineer. I am interested in Swift, Kotlin, Firebase, Data Structures, ASO & On Solving Real World Problems.