Logo for tanaschita.com

How to use a Connectable publisher in Combine

Learn how to avoid data loss by using Combine's ConnectablePublisher.

13 Dec 2021 · 2 min read

When working with publishers in Combine, we sometimes need more control over the timing when values start emitting. Combine provides the ConnectablePublisher type which doesn’t produce any elements until we call its connect() method.

We can convert any publisher or subscriber into a ConnectablePublisher by calling the method makeConnectable().

Let's look at an example.

let publisher = Just(5)
subscriber1 = publisher.sink { newValue in
print(newValue)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.subscriber2 = publisher.sink { newValue in
print(newValue)
}
}
Sponsorship logo
Join the FREE iOS Architect Crash Course (for a limited time!)
If you’re a mid/senior iOS developer who’s looking to improve both your skills and salary level, then join this 100% free online crash course. Hurry up because it's available only until November 27th!
Click to get it now

In the example above, subscriber2 does not receive the emitted value 5. In case we need to make sure both subscribers receive the value, we can adjust the example as follows:

let publisher = Just(5).makeConnectable()
subscriber1 = publisher.sink { newValue in
print(newValue)
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.subscriber2 = publisher.sink { newValue in
print(newValue)
}
self.connection = publisher.connect()
}

Now, the value will be emitted after we call the connect() method on the publisher, so both subscribers receive it.

How to automatically connect with first subscriber

In case we want a ConnectablePublisher to start emitting values right after the first subscriber subscribes, it provides the autoconnect() method.

self.timerSubscriber = Timer.publish(every: 5, on: .main, in: .default)
.autoconnect()
.sink() { date in
print (date)
}

In the example above, the publish method of Timer returns a ConnectablePublisher. By calling autoconnect() the timer starts sending date values as soon as we subscribe.

Sponsorship logo
Join the FREE iOS Architect Crash Course (for a limited time!)
If you’re a mid/senior iOS developer who’s looking to improve both your skills and salary level, then join this 100% free online crash course. Hurry up because it's available only until November 27th!
Click to get it now

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

combine

swift

ios

Backpressure in Combine

Learn what backpressure is and how to apply it in Combine.

06 Dec 2021 · 8 min read

Latest articles and tips

© 2022 tanaschita.com

Privacy policy

Impressum