DataTaskPublisher to Future or AnyPublisher for API Client method

I’ve just finished reading Combine: Asynchronous Programming with Swift. I really enjoyed it. Great disposition, pedagogic and clear, high-quality sample code. Well done! I Really learned a lot!

I’m implementing (for the first time) a web service client in Swift using the Combine framework.

For a method that makes a single call to a web service and then closes the connection, returning a Future seems more appropriate to me than returning an AnyPublisher. To me a Future suggests that this method should be called repeatedly. An AnyPublisher suggests that the publisher should be retained and monitored for future values/events.

In Flutter, a single async value would be a “Future” and multiple async values would be a “Stream”. In the WWDC 2019 talk: “Introducing Combine” Apple presents a slide that hints at Futures as the async version of a single sync value. And Publishers as the async version of sync arrays.

In the book I notice that you suggest web service methods returning different types of AnyPublishers. E.g. the web service client for hacker stories and dad jokes. Could you elaborate on this design choise (the return type, not the API’s ;)?

Is the design choise a pragmatic one? It’s just easier to return erase a DataTaskPublisher to an AnyPublisher and just return that. Mapping a DataTaskPublisher pipeline to a Future dosen’t seem to be straight forward at all.

I understand that Futures in fact are Publishers, even though there are subtle technical nuances to consider (greedy/lazy, sharing of values to multiple subscriber etc).

Any complementary thoughts appreciated! Thanks.

1 Like

The big difference in Combine between the two is that Future is being subscribed immediately upon creation - it’s an immediate task that returns one result. Publishers as you know, are subscribed whenever there’s a particular subscriber to consume the emitted values.

In a book like this we would often show how to do something multiple ways so I wouldn’t dwell too much on the choice between a future or a publisher, it’s likely that we wanted to showcase how each of them is used in a real-life scenario and that’s why they made their way into the chapters’ projects.

Thanks @icanzilb.

I think what prompted my question was the absence of Futures in the sample code, rather than a mix and match between Futures and AnyPublishers. Just wanted to know if that choice was an academic choice or a pragmatic one.

Having worked some more with combine since I posted my question I think AnyPublishers are the way to go from a pragmatic point of view. Making the publishers return individual pieces of data rather then arrays of data makes it less awkward.

Thanks for responding.

2 Likes