Chapter 14.3: Complexity vs easier alternative?

When I first read the task for mergedStories I initially thought about using a flatMap and wondered about the complexity used in that function (creating array, remainder, merge).

So I tried a different version that looks like this (trying to understand flatMap again):

func mergedStories2(ids: storyIDs: [Int]) -> AnyPublisher<Story, Error> {

Using this much simpler looking function I get nearly the same result, although sometimes the order of stories printed differs (1000, 1002, 1001).

since I can’t really say I understood everything in detail I ask: what’s the problem with my function, why does the order differ sometimes (depending on web request latency) and whether this could also happen in the original approach, and how to avoid that.

Still trying to understand all the impacts.
Thanks for any insights.

Hey, that’s a great questions - your solution is just a different way to implement similar functionality like the mergedStories(ids:) from the book. Sometimes the code samples in a book are focused on showcasing some specific functions and aren’t focused on the shortest solution so no worries.

If you want to guarantee the order of the elements in your downstream I’d say you’ll have to first collect them all - i.e. off the top of my head I’ll get the enumerated collection of the IDs so I have pairs of (index, ID), then use flatMap() to map those into (index, Result), then use a collect() to collect all those pairs in an array, and then call sorted() on the array and get the results in the desired order.

1 Like