/* * Retry Transient Errors * Catch and Replace Persistent Errors * ----------------------------------- */let fallbackURL: URL ="some fallback url"let fallbackSession = URLSession.sharedsession .dataTaskPublisher(for: url)// ⭐️ transient errors: .retry(1)// ⭐️ persistent errors:// use catch(_:) to replace error with another publisher// use replaceError(with:) to replace error with an element you provide .catch() { _in fallbackSession.dataTaskPublisher(for: fallbackURL) } .sink(receiveCompletion: { print("Received completion: \($0).") }, receiveValue: { print("Received data: \($0.data).") })
Scheduling Operators
/* * Move Work Between Dispatch Queues With Scheduling Operators * ----------------------------------------------------------- */session .dataTaskPublisher(for: url)// ⭐️ specify how you want later operators in the chain and your subscriber,// to schedule the work .receive(on: DispatchQueue.main) .sink(receiveCompletion: { print ("Received completion: \($0).") }, receiveValue: { print ("Received data: \($0.data).") })
URL session starts loading data as soon as the URLSession.DataTaskPublisher has unsatisfied demand from a downstream subscriber. In this case, that happens when the first sink subscriber attaches.
If you need extra time to attach other subscribers, use .makeConnectable() to wrap the Publishers.Share publisher with a ConnectablePublisher.
After connecting all subscribers, call .connect() on the connectable publisher to allow the data load to begin.