Swift Combine Handling Multiple Publishers, Level Up Your Career as an iOS Developer!

When developing, it is rare to use only one publisher. Sometimes you will handle a single event from more than one publisher. Today’s tutorial will cover the functions combineLatest, merge(with), and zip, which are used when using more than one publisher.

combineLatest

combineLatest

combineLatest subscribes to an additional publisher. Before you look, you need to remember that “when you receive an ouput from both publishers, closures get called”.

returns multiplication of first and second as a result

The code is simple. Multiply the integers in pub1 and pub2 to get the result.

return first * second will never get called

Sent 2 to pub1. But nothing happens. Why?

combineLatest calls the closure “when it receives an ouput from both publishers”.

Since it received a value from pub1, but no value from pub2, the closure cannot be executed.

merge

merge example

Merge literally means merge. It’s just a role that really merges them into one stream. This is useful when you want to treat two publishers as one publisher. Unlike combineLastest, when you receive one output from one publisher, it gets called.

one event triggers closure

As I told you, unlike combineLastest, one event triggers closure.

zip

A zip combines elements from different publishers and provides element pairs as tuples.

Because zip “combines” values ​​from each publisher, ike combineLastest, if neither publisher has a value, it will not emit a value. And the bundled publishers are the “oldest-used” events from each publisher.

zip example

zip returns tuple value and it never gets called unless it receives values from each publisher. Because it makes it a couple,

Conclusion

  • Use combineLatest, when you have multiple publishers that rely on each other.
  • Use merge when you need to use more than one publishers as a single publisher.
  • Use zip when you need key-value merged data.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
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!