Combine Framework In Swift -1

Keerthiraj Su
2 min readApr 20, 2021

In Apple’s words: “The Combine framework provides a declarative approach for how your app processes events. Rather than potentially implementing multiple delegate callbacks or completion handler closures, you can create a single processing chain for a given event source. Each part of the chain is a Combine operator that performs a distinct action on the elements received from the previous step.”

Combine is a reactive library introduced by apple in WWDC 2019. Though its bit robust to understand but good learning curve. Support for combine is from iOS 13, So we can start learning and be ready when the library gets matured.

Main Parts of combine

1)Publisher

2)Subscriber

3) operators

We learn more about these as we move forward and other topics like operators, custom Subscribers, Future and Promise and the list goes on..

Publisher : Types which emit the values which can be synchronous or asynchronous.

Subscriber: Types which Receive values emitted by publisher.

Operators: Methods that perform an operation on values coming from a publisher.

let _ = Just("Hello world")
.sink { (value) in
print(value + "now")
}

In above example “Just” is a kind of punblisher which emits one value(String , float..etc). sink is the call back where we we changing the output by appending “now” Output “Hello worldnow”.

Lets look at few more example: Array and NSNotification

[1,2,3,4,].publisher.sink(receiveValue: {
print($0)
})

NSNotification:

let notification = NSNotification(name: .NSSystemClockDidChange, object: nil)
NotificationCenter.default.publisher(for: .NSSystemClockDidChange)
.sink(receiveValue: {(value) in
print (value)
})
NotificationCenter.default.post(notification as Notification)

In the Above example we we created a notification which fires when time changes(System time) We added publisher for that notification type then subscribed to the value emitted by publisher, Which will be received inside sink closure.

Note: Combine support is added to many components when you import Combine library.

We can write separate publisher and subscriber blocks and build upon them. which will be helpful code Readability

let arrayPublisher = [1,2,3,4,].publisher
.prefix(2)

let subscriber = arrayPublisher
.sink{(value) in
print(value)
}

Which gives output 1,2 . Here Prefix is a operator

Note : Subscriber(AnyCancellable) should be in memory when the publisher emits the output, In simple words it shouldn't be a local variable.

Using subscriber instance we can cancel subscription

subscriber.cancel()

On Next part we will see how to make asynchronous API calls with Combine and deep dive in to custom operators and subscribers.

Keep Coding. Keep Improving !!

--

--

Keerthiraj Su

Software Engineer Shuffling between iOS and Gaming