In Apple parlance,Combine is:

a declarative Swift API for processing values over time

This sentence contains three of Combine’s core elements:

  • declarativeThe syntax for Combine is declarative
  • valuesIndicates that the data processed by Combine is not isolated, but multiple and complex
  • over timeRepresents the data to be processed with time effects, that is, a stream of events with a time sequence

In summary, Combine is a declarative programming framework specifically designed to handle the flow of events.

It is important to explain why this is an event stream rather than a data stream, as in a scenario like this:

  1. When the user enters a keyword
  2. duplicate removal
  3. Sending network Requests
  4. Error checking
  5. Data parsing

These are the five events, each with its own inputs and outputs. If we link them together, they form a data flow pipeline, or data flow. So what does the code look like?

enum NetworkError: Error {
    case invalidResponse
}

struct Student: Codable {
    let name: String
    let age: Int
}

let publisher = PassthroughSubject<String.Never>()

cancellable = publisher
    .removeDuplicates()
    .flatMap { value in
        return URLSession.shared.dataTaskPublisher(for: URL(string: "https://xxx.com?name=\(value)")!)
    }
    .tryMap { (data, response) -> Data in
        guard let httpResp = response as? HTTPURLResponse, httpResp.statusCode = = 200 else {
            throw NetworkError.invalidResponse
        }
        return data
    }
    .decode(type: Student.self, decoder: JSONDecoder())
    .catch { _ in
        Just(Student(name: "", age: 0))
    }
    .sink(receiveCompletion: {
        print($0)
    }, receiveValue: {
        print($0)
    })

publisher.send("Zhang")
Copy the code

Functional Reactive Programming Functional Reactive Programming

There are many articles on the web that describe functional responsive programming in detail, but it is still confusing to read. In this section, I try to give a brief introduction to functional responsive programming.

As shown above, understanding functional and responsive programming requires understanding functional and responsive programming separately.

Functional programming is easy to understand, starting with two important concepts:

  • Give the mathematical properties of functions
  • Granting first-class citizenship

So what do I mean by functional mathematics? Quite simply, anything with mathematical properties must be logically rigorous and computationally secure. In the world of functional programming, functions must never modify the state of a variable, and an input must produce a fixed output.

When a function is safe, it can participate in the operation and transfer of data. Therefore, function status is promoted to first-class citizen, which can be used as either an argument or a return value of another function.

Learn more about Swift functional programming here: Learn Swift Functional programming

When it comes to reactive programming, it’s a little bit harder to understand, because a lot of developers are used to writing functions, not necessarily reactive code. A response essentially implies a Stream.

At this point, the input data is no longer dead data, but changes over time. Different inputs produce different outputs, so we need to respond to these outputs.

Here’s an example:

var a = 1
var b = 2

c = a + b

/// c == 3

a = 2
Copy the code

In the code above, we think of a and B as input data and C as output data. When I change a, the output data c does not change. This is not responsive.

The problem that reactive programming solves is the flow of data, especially when data flows asynchronously, or more complex when multiple data flows asynchronously.

** Functional responsive programming is when we combine functional and responsive programming. ** Looks like this:

Think of data processing as a black box of functions,

You can also think of it as a flow pipe, where we just have to lay out the right pipe in advance, wait for the data to come in, and then respond.

When do you use Combine?

The core of the Views refresh mechanism in SwiftUI is Source of Truth, that is, the content displayed by Views completely depends on its state. When the state changes, the UI also changes. Although SwiftUI and Combine are natural Allies, the Combine can still be used in other frameworks.

If we look at problems from the most macroscopic perspective, we can consider using Combine when we meet the following two problems:

  • Asynchronous tasks
  • The data will change over time

In daily development, there are a lot of asynchronous tasks. Combine is naturally a good hand at handling asynchronous tasks, which will be explained in detail in later articles.

conclusion

Combine was introduced in iOS13, so the minimum system version required to develop programs using Combine is iOS13. Both UIKit and SwiftUI can be used. SwiftUI, in particular, truly separates logic and UI with the Combine.