In this article, we will explore six handy combining operators in Combine. We will do so by quickly experimenting with each of them in an Xcode Playground.
The source code is available at the bottom of the article.
Without further ado, let’s get started.
This group of operators allows us to prepend events, values, or other publishers to our source publisher:
import Foundation
import Combine
var subscriptions = Set<AnyCancellable>()
func prependOutputExample() {
let stringPublisher = ["World!"].publisher
stringPublisher
.prepend("Hello")
.sink(receiveValue: { print($0) })
.store(in: &subscriptions)
}
The result is Hello
and World!
printed in sequential order:
Let’s now prepend another publisher of the same type:
func prependPublisherExample() {
let subject = PassthroughSubject<String, Never>()
let stringPublisher = ["Break things!"].publisher
stringPublisher
.prepend(subject)
.sink(receiveValue: { print($0) })
.store(in: &subscriptions)
subject.send("Run code")
subject.send(completion: .finished)
}
#mobile #programming #swift #ios #xcode