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)
}
}

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.

Image of books
Further reading: Swift Power Pack
For further reading, check out the Swift Power Pack books by Paul Hudson. The bundle delivers six books from beginner to advanced around Swift topics.

Newsletter

Receive a monthly newsletter about the latest articles and tips.

Image of a reading marmot

Related tags

Written by

Articles with related topics

Latest articles and tips