Swift Combine: switchToLatest()

Let’s talk about a little bit of a more complicated combination operator, switchToLatest(). As the name suggests, switchToLatest() operator allows you to actually switch to a different publisher on the fly.

switchToLastest()

I created two PassthroughSubject. They take in String. And another third publisher which takes in PassthroughSubject<String, Never>. You can think of it as a parent publisher.

One of the things that you have to keep in mind is that publishers , the parent publisher, when it sinks, it gives you String not PassthroughSubject<String, Never>.

When the parent publisher sends an event, you can think of it as parent publisher subscribing to a child publisher. So whenever an event is generated from a child publisher, it will be captured by the parent publisher.

But what happens if your parent publisher subscribes to second child publisher with publishers.send(publisher2)? In this case, because you are using switchToLatest() operator, you will receive the event from the publisher2.

You must keep in mind, after your parent publisher subscribes to the second child publisher, publisher1’s event is ignored. Or you can simply call publishers.send(publisher1) to receive events from publisher1.

Practical Example

I prepared cat, dog, tiger images locally. getImage() method returns publisher asynchronously with image.

Imagine taps.send() is actually a tap event from a user. Whenever users tap on something with taps.send(), it switches image. Using switchToLatest() operator, you can finally get the image from .sink() method.

Conclusion

  • switchToLatest() takes publishers.
  • Whenever send() occurs, it switches to the latest publisher and receives values from the latest publisher.

--

--

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

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!