Creating a custom Combine Publisher to extend UIKit

Antoine van der lee 🇳🇱
The Startup
Published in
5 min readJul 2, 2019

--

A Custom Combine Publisher can add missing functionalities to UIKit elements you use every day. A lot of boilerplate code can be removed and implementations can be simplified.

A simple example is responding to UIControl events. The standard library comes with a few great extensions to, for example, decode JSON easily and assign values to key paths. Unfortunately, responding to UIControl events is not in there. Although you might expect it in a later update, let's use it as an example to create our own custom Combine Publisher.

Just getting started with Combine? You might want to first take a look at Getting started with the Combine framework in Swift or my Combine Playground.

Creating a custom Combine Subscription

Before we create our custom Combine Publisher, we first need to create our own Combine subscription type. For this, we need to conform to the Subscription protocol which inherits from the Cancellable protocol. The latter gives us the cancel() method which is required to handle the cancellation of a subscription.

Let’s take a look at the code and break it down after:

/// A custom subscription to capture UIControl target events.
final class UIControlSubscription<SubscriberType: Subscriber, Control: UIControl>: Subscription where SubscriberType.Input == Control {
private var subscriber: SubscriberType?
private let control: Control

init(subscriber…

--

--

Antoine van der lee 🇳🇱
The Startup

iOS Developer @WeTransfer — Follow me on twitter.com/twannl for more tips & tricks — Blogging weekly at https://avanderlee.com — Clap & hold for a surprise!