Using Delegate Pattern with Combine

Cory D. Wiles
1 min readJan 24, 2020

The Tried and True Delegate Pattern

The delegate pattern has long been very prominent on Apple’s platforms. Delegation is used for everything from handling table view events using UITableViewDelegate, to modifying cache behavior using NSCacheDelegate. The core purpose of the delegate pattern is to allow an object to communicate back to its owner in a decoupled way. By not requiring an object to know the concrete type of its owner, we can write code that is much easier to reuse and maintain.

Source: https://www.swiftbysundell.com/articles/delegation-in-swift/

Combining the “old” and “new”

While I was working on the SpokestackRSSExample I wanted to leverage as many of the new iOS 13 API’s as possible, while still giving developers the option of using the delegate pattern. Supporting the delegate pattern is pretty straight forward and battle tested:

let session = URLSession(configuration: URLSessionConfiguration.default)
var request: URLRequest
do {
request = try createSynthesizeRequest(input)
} catch TextToSpeechErrors.apiKey(let message) {
self.delegate?.failure(error: TextToSpeechErrors.apiKey(message))
return
} catch let error {
self.delegate?.failure(error: error)
return
}

Unfortunately, working with a Publisher this wouldn’t work…so how do you capture the success or failure of creating the synthesize request and sending that result back to the delegate? Wrap the creation request in it’s own publisher, use the flatMap operator to get the value which can be passed down to the dataTaskPublisher. Alas you now have a new pattern with the same information as using delegate.

--

--

Cory D. Wiles

I code stuff in Swift. I also raise children, workout, and make a perfect old fashioned.