Nothing special so far, just some basic Codable elements, and a simple error, because hell yeah, we want to show some error if something fails. ❌

The traditional way

Doing an HTTP request in Swift is pretty easy, you can use the built-in shared URLSession with a simple data task, and voilá there's your response. Of course you might want to check for valid status code and if everything is fine, you can parse your response JSON by using the JSONDecoder object from Foundation.

Data tasks and the Combine framework

Now as you can see the traditional "block-based" approach is nice, but can we do maybe something better here? You know, like describing the whole thing as a chain, like we used to do this with Promises? Beginning from iOS13 with the help of the amazing Combine framework you actually can go far beyond! 😃

In a nutshell, this time we check the response code and if something goes wrong we throw an error. Now because the publisher can result in an error state, sink has another variant, where you can check the outcome of the entire operation so you can do your own error thingy there, like displaying an alert. 🚨

Assign result to property

Another common pattern is to store the response in an internal variable somewhere in the view controller. You can simply do this by using the assign function.

Very easy, you can also use the didSet property observer to get notified about changes.

Group multiple requests

Sending multiple requests was a painful process in the past. Now we have Compose and this task is just ridiculously easy with Publishers.Zip. You can literally combine multiple requests togeter and wait until both of them are finished. 🤐

Request dependency

Sometimes you have to load a resource from a given URL, and then use another one to extend the object with something else. I'm talking about request dependency, which was quite problematic without Combine, but now you can chain two HTTP calls together with just a few lines of Swift code. Let me show you:

Conclusion

Combine is an amazing framework, it can do a lot, but it definitely has some learning curve. Sadly you can only use it if you are targeting iOS13 or above (this means that you have one whole year to learn every single bit of the framework) so think twice before adopting this new technology.

You should also note that currently (b6) there is no upload/downloadTaskPublisher, maybe in a later beta seed we'll see something like that. Fingers crossed. 🤞

I really love how Apple implemented some concepts of reactive programming, I can't wait for Combine to arrive as an open source package with linux support as well. ❤️