Example: zip two publishers
class Demo12 {
var cancellables = Set< AnyCancellable>()
func example(of: String) {
let pub1 = PassthroughSubject<Int, Never>()
let pub2 = PassthroughSubject<String, Never>()
pub1
.zip(pub2)
.sink(receiveCompletion: { _ in print("Completed") },
receiveValue: { print("P1: \($0), P2: \($1)") })
.store(in: &cancellables)
pub1.send(1)
pub1.send(2)
pub2.send("a")
pub2.send("b")
pub1.send(3)
pub2.send("c")
pub2.send("d")
pub1.send(4)
pub1.send(completion: .finished)
pub2.send(completion: .finished)
}
}
let d = Demo12()
d.example(of: "good")
Example 2 (Apple official): it zip more publishers
let numbersPub = PassthroughSubject<Int, Never>()
let lettersPub = PassthroughSubject<String, Never>()
let emojiPub = PassthroughSubject<String, Never>()
let cancellable = numbersPub
.zip(lettersPub, emojiPub)
.sink { print("\($0)") }
numbersPub.send(1)
numbersPub.send(2)
numbersPub.send(3)
lettersPub.send("A")
emojiPub.send("😀")
lettersPub.send("B")
emojiPub.send("🥰")