Introducing Combine, the perfect compatibility with SwiftUI

The more I use SwiftUI, the more I think that understanding of Combine is essential to understand SwiftUI and use it in depth. Combine is a framework created by Apple, and many say that it can be thought of as ‘Apple version of RxSwift’.

Combine

So, what Combine is, you can find out more in Apple’s official documentation. In summary, Combine is a framework that provides a Declarative Swift API for handling values over time.

Apple has already applied the Combine API to Timer, NotificationCenter, and Core Data. The new SwiftUI framework is designed to make it easier to apply Combine. The hierarchy of Combine is shown in the figure below.

combine-introduction

Advantages of Combine

Why is the Combine code better than the existing code?

First of all, Combine is implemented at the system level, so users other than Apple use parts that cannot be used. And there are more automatic implementations than using old methods like IBActions or delegates. It also makes the code easier to maintain by eliminating badly readable techniques like nested closures.

After all, Combine is not essential, but it does help improve the quality of your code.

Asynchronous Programming

Even though async/await is becoming popular nowadays, Combine makes asynchronous programming easier and safer.

Apple is already using asynchronous programming in things like NotificationCenter, Delegate pattern, Grand Central Dispatch, Closures. Asynchronous programming may be required for the following multi-threaded tasks.

// Thread 1
var name = "Hohyeon"
print(name)

// Thread 2
name = "Moon"

// Thread 1
name += " Moon"
print(name)

The name value of this code may be Hohyeon Moon depending on the situation and Moon Moon at other situation. So we need asynchronous programming.