This is part of the Declarative Programming with Combine learning path. View Path.
Who is this for?
This course is useful if you already have a basic understanding of Combine, and are interested in learning about more advanced Combine features. If you are familiar with Swift’s URLSession class, error handling, and Xcode testing, it will help you understand the examples.
- Error Handling
Part 1: Intermediate Combine
Combine comes with 2 special operators,
that help you fetch data from the network in your Combine pipeline, and decode that
data using Swift’s built in decoders such as
Publishers in Combine are usually passed by value, since they are structs; however, you can use the
built in Combine operator
share() to pass them by reference, establishing one true subscription and simply
sharing the data with other subscribers as they come along. Want to wait until all of the subscribers are
ready before starting the data flow?
multicast() allows you to do just that, and start the data when you are ready.
The Subscriber protocols allows developers to define the maximum amount of data that subscriber will accept each time it receives a new value from the Publisher, allowing you to dynamically manage backpressure. However, the adjustment is additive, and must be positive, meaning the max can only go up.
Operators such as
tryMap erase any error types that are encountered during execution of the code within the operator. The
mapError operator lets developers maintain knowledge of errors encountered, passing them down the Combine pipeline.
Each publisher gets the ability to retry sending their data if errors are encountered - something commonly seen when
working with getting data from the network. The
retry() operator can be used to retry the publisher a certain number of times
before failing, and the
catch() operator can be used to fall back to a default set of data if all else fails.
As with all other code, your Combine pipeline code can, and should be, tested. The Given-When-Then pattern is a great way to layout your test code, ensuring that your code works as intended.