Replace Delegation With Combine in Swift 5

Tram Ho

Getting Started

Consider the following two monitors:

On the first screen, displays a list of items. When the button “Add item” is pressed, the second screen will be displayed, allowing new items to be added. The traditional approach to doing this is as follows:

ItemsViewController

As we have seen, inside the addButtonTapped (sender 🙂 function, we create the AddItemViewController and assign self to its delegate property.

Through AddItemViewControllerDelegate to get information of newly added item and update to tableView .

AddItemViewController

Here, in the doneButtonTapped (sender 🙂 function, we’ll run the delegate didAddItem (item 🙂 and dismiss viewController.

How can it be simpler? What if we don’t need any delegate protocol and can still track the update to add new item inside the ItemsViewController?

Combine’s publishers and observers will help us to do this

Using Combine

First delete the AddItemViewControllerDelegate and create a PassthroughSubject of type String:

As can be seen here, we have sent a new value to the newItem inside the doneButtonTapped (sender 🙂 function .

Now that AddItemViewController has a valid publisher, we can subcribe it inside ItemViewController.

When a new value is sent to the newItem object inside the AddItemViewController , we update the tableView inside the .handleEvents operator.

Note that to prevent the subcription from being released immediately, let’s create a subcription property to store our subscription.

Finally we can replace the traditional delegate approach with Combine.

See more about Combine: https://developer.apple.com/documentation/combine

Share the news now

Source : Viblo