How to use a Connectable publisher in Combine
Learn how to prevent data loss by using Combine's ConnectablePublisher.
18 Nov 2024 · 3 min read
When working with publishers in Combine, there are situations where we need precise control over when values start emitting. By default, Combine publishers begin emitting as soon as they are created, which can lead to subscribers missing some values if they aren't connected in time.
This is where Combine’s ConnectablePublisher comes in. A ConnectablePublisher holds off emitting values until its connect() method is called, giving us more control over when subscribers start receiving values.

Let's look at an example.
let publisher = Just(5)subscriber1 = publisher.sink { newValue inprint(newValue)}DispatchQueue.main.asyncAfter(deadline: .now() + 1) {self.subscriber2 = publisher.sink { newValue inprint(newValue)}}
Here, subscriber2 misses the emitted value 5 because the Just publisher emits it immediately, and subscriber2 subscribes too late.
Solving the issue with ConnectablePublisher
To ensure both subscribers receive the value, we can convert the publisher to a ConnectablePublisher by calling makeConnectable() and controlling when it starts emitting values using the connect() method:
let publisher = Just(5).makeConnectable()subscriber1 = publisher.sink { newValue inprint(newValue)}DispatchQueue.main.asyncAfter(deadline: .now() + 1) {self.subscriber2 = publisher.sink { newValue inprint(newValue)}self.connection = publisher.connect()}
Now, the publisher will only emit the value after connect() is called, ensuring both subscribers receive the value.
How to automatically connect with first subscriber
If 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 inprint (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.



Newsletter
Like to support my work?
Say hi
Related tags
Articles with related topics
Latest articles and tips



