swiftui-notes icon indicating copy to clipboard operation
swiftui-notes copied to clipboard

flatMap vs map + switchToLatest

Open mycroftcanner opened this issue 6 years ago • 1 comments

If you want to use data provided by a publisher as a parameter or input to creating this publisher, there are two common means of enabling this:

Using the flatMap operator, using the data passed in to create or return a Publisher instance. This is a variation of the pattern illustrated in Using flatMap with catch to handle errors.

Alternately, map or tryMap can be used to create an instance of a publisher, followed immediately by chaining switchToLatest to resolve that publisher into a value (or values) to be passed within the pipeline.

The difference between the two alternative ways to create a publisher should be clearer.

When is it okay to use flatMap and when is it okay to use switchToLatest?

This is quite confusing.

mycroftcanner avatar Nov 24 '19 02:11 mycroftcanner

That's a really good question, to which I don't have a definitive answer - and didn't feel like I could assert one without better internal knowledge.

To my experiments, the two systems appear to operate identically - although I didn't benchmark them to any insane degree to see if there was a slight performance difference between using the two structures. In practice, I think they're symmetrical paths and its a choice of pattern that you prefer, but I'm not sufficiently confident in my understanding to assert that in the book. I also don't have any inside information into the creation/underlying code of Combine to know if there's a subtle difference there that should be called out, so I'm afraid I've just them both as open parallel paths.

heckj avatar Nov 24 '19 17:11 heckj