Swift Combine: merge() operator

KD Knowledge Diet
1 min readJan 24, 2023

--

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.

--

--

KD Knowledge Diet
KD Knowledge Diet

Written by KD Knowledge Diet

Software Engineer, Mobile Developer living in Seoul. I hate people using difficult words. Why not using simple words? Keep It Simple Stupid!

No responses yet