Reactive Programming in iOS with Combine

Feb 4 2021 · Swift 5.3, macOS 11.0, Xcode 12.2

Part 3: Combining Operators

18. More Combining Operators

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 17. Challenge: Append and Prepend Next episode: 19. Operator Examples

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Transcript: 18. More Combining Operators

Now let’s talk about some more complex combining operators. I’ll explain each of them with a marble diagram, and then we’ll see them in a demo.

switchToLatest is complex, but very useful. It lets you switch entire publisher subscriptions on the fly while canceling the existing publisher subscription. You can only use it on publishers that themselves emit publishers. This marble diagram shows that the publisher on the top of the operator is actually a Publisher of Publishers. numbers1 is published first, and while values are being emitted, the publisher switches to numbers2, and cancels publisher 1.

The merge(with:) operator interleaves emissions from different publishers of the same type. In the marble diagram you see the original publisher, which emits 1, 2, and 4, gets merged with publisher 2, which emits 3 and 5. The sequence 1,2,3,4,5 is sent downstream.

combineLatest not only lets you combine values from 2 publishers, it also allows for those values to be of separate types. combineLatest, however, doesn’t interleave like merge does; instead, it forms a tuple of the latest values from each publisher and emits that tuple to the downstream consumer. The catch here is that each publisher must have emitted at least one value for the combineLatest to emit anything.

Finally, zip emits tuples like combineLatest, but forms the tuples of the same index across all publishers. The marble diagram shows the first tuple emission once the original publisher and publisher2 have emitted their first value. The next tuple occurs after both have emitted their second values, and so on.

With those concepts in hand, let’s look at these operators in a demo, which we’ll do in the next episode.