Member-only story

A simple Event handler in Swift

Mihail Dimitrov
4 min readSep 21, 2023

Background

About five years ago, I started delving into TypeScript, developing applications that required me to focus on asynchronous operations and their outcomes.

Even though there are affirmed methods to do that, I wanted to play around with the abilities of the script, so I created a class that would allow me to track my flow in the simplest way I could think of.

The Theory

I wanted to execute subscribed piece(s) of code (an arrow function or a closure) whenever an event is triggered.

As a first step, I defined the type that would represent an event subscription handler. I called it the Event Handler, which only has one property of type closure (handle), taking any arguments it needs.

The second step is to define the event consumer — the Event class. It consists of:

  • A Subscriptions array of elements of type EventHandler, which stores all the events that need to be fired upon dispatch;
  • A Subscribe method, which takes an EventHandler instance as an argument and appends it to the Subscriptions array;
  • A Subscribe Once method, which also takes an EventHandler instance as an argument but wraps it in another EventHandler that unsubscribes itself before delegating the execution…

--

--

Mihail Dimitrov
Mihail Dimitrov

Written by Mihail Dimitrov

I am a software developer with many passions, the largest one being life itself!

No responses yet