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
Preparing for a technical iOS job interview - updated for iOS 18
Check out my book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift, SwiftUI, Combine, HTTP Networking, Authentication, SwiftData & Core Data, Concurrency with async/await, Security, Automated Testing, Machine Learning and more.
LEARN MORE

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
Preparing for a technical iOS job interview - updated for iOS 18
Check out my book on preparing for a technical iOS job interview with over 200 questions & answers. Test your knowledge on iOS topics such as Swift, SwiftUI, Combine, HTTP Networking, Authentication, SwiftData & Core Data, Concurrency with async/await, Security, Automated Testing, Machine Learning and more.
LEARN MORE

Newsletter

Image of a reading marmot
Subscribe

Like to support my work?

Say hi

Related tags

Articles with related topics

combine

swiftui

swift

ios

How to delay server requests for user's search query with SwiftUI and Combine

Learn how to debounce on a practical example.

15 Jul 2024 · 5 min read

Latest articles and tips

© 2024 tanaschita.com

Privacy policy

Impressum