Swift Combine

swift combine
 

Last year at the WWDC2019, Apple has decided to focus on building and releasing their own functional reactive programming framework, Swift Combine. The Combine framework provides a declarative Swift API for processing values over time.

 

Several Foundation types expose their functionality through publishers, including Timer, NotificationCenter, and URLSession. Combine also provides a built-in publisher for any property that’s compliant with Key-Value Observing.

 

I wanted to introduce some of its ideas and show how to integrate it into code with simple example. But first of all I will present you with three important protocols:

 

Protocol publisher:

 
Declares that a type can transmit a sequence of values over time.

There are four kinds of messages:

  • subscription – A connection between publisher and subscriber.
  • value – An element in the sequence.
  • error – The sequence ended with an error(.failure(e)).
  • completion – The sequence ended successfully (.finished).

Both .failure and .finished are terminal messages.

 

Protocol subscriber:

 

A protocol that declares a type that can receive input from a publisher (subscriber can receive emitted elements from a Publisher).

 

A Subscriber acts on elements as it receives them. Publishers only emit values when explicitly requested to do so by subscribers.

 

Protocol cancellable:

A protocol indicating that an activity or action may be canceled.

 

Calling cancel() frees up any allocated resources. It also stops side effects such as timers, network access, or disk I/O.

 
 

Another important thing to know, in RxSwift subscription results in a Disposable, which allows you to stop the subscription, Swift Combine does not have this. Instead, if you do not want to receive further updates, you can just dereference the Publisher chain. Apple calls a Cancellable.

Leave a Reply