Basics of the Combine framework
With graphic examples
This article introduces the basics of Combine, a framework that allows you to write solid, safe, and well-tested asynchronous code. In this article, we will focus on its theoretical fundaments and key points, served with graphic examples. Something essential before writing any line of async code.
First things first: Asynchronous code
If we check Apple docs, we’ll find the following description about Combine: “Customize handling of asynchronous events by combining event-processing operators”. That’s very accurate actually but if you’re getting started with Combine it can be a bit complex or abstract. In this way, let’s start with the concept of asynchronous code.
First, a program that runs synchronously executes its lines sequentially. Checkout bellow example. There is only one thread of execution, so you easily know the state of your data. In that case, output will be 2
.
var myNumber = 1
myNumber+=1
print(myNumber)
Create now an asynchronous version of the previous code. In that case, we’ll schedule that code lines at some random time. Code is running concurrently on different core, thus we will have different results each time we execute the code. Sometimes it prints 1
and other times 2
.