Swift Combine: merge() operator
Let’s go ahead and take a look at another combining operator and this is called merge operator.
merge()
operator, just as the name implies, is going to merge the different events from different publishers.
merge()
let publisher1 = PassthroughSubject<Int, Never>()
let publisher2 = PassthroughSubject<Int, Never>() publisher1.merge(publisher2)
.sink {
print($0)
}publisher1.send(0) // 0
publisher2.send(1) // 1
I prepared two publishers. Note that if you want to merge publishers, the both publishers should have the same type. In this case, <Int, Never>
is indicating the same type.
By simply calling merge(publisher)
, you can now receive events from the both publishers.
You can simply check that when you publisher an event with publisher1
, its values will come through .sink
, likewise when you emit a value from publisher2
, it also goes down to sink
.
Conclusion
merge()
operator allows you to merge multiple publihsers.- You can receive events from merged publisher.