iosswiftcombinensurlsessiondatatask

A question about URLSessionDataTask and Combine in Swift


In an article, I saw a code snippet like below:

extension URLSessionDataTask: Cancellable {}

extension URLSession: NetworkService {
   public func fetchData(with request: URLRequest, handler: @escaping (Data?, URLResponse?, Error?) -> Void) -> AnyCancellable {
      let task = dataTask(with: request, completionHandler: handler)
      task.resume()
      return AnyCancellable(task)
   }
}

There are several things that I do not understand:

  1. What is the purpose of making URLSessionDataTask conform to 'Cancellable' protocol;
  2. If URLSessionDataTask conforms to 'Cancellable' protocol, why does not it implement the methods that 'Cancellable' protocol requires;
  3. When I check the initialiser of AnyCancellable, there is no initialiser which accepts an argument, so what does 'AnyCancellable(task)' do here and is it correct?

Appreciate any help.


Solution

    1. What is the purpose of making URLSessionDataTask conform to 'Cancellable' protocol?

    So that you could use AnyCancellable. AnyCancellable initializer only works with types conforming to Cancellable.

    1. If URLSessionDataTask conforms to 'Cancellable' protocol, why does not it implement the methods that 'Cancellable' protocol requires;

    Cancallable requires there to be a method cancel and store(in:). cancel already exists on URLSessionTask - a base class of URLSessionDataTask, and store(in:) is implemented as an extension on Cancellable providing a default implementation.

    1. When I check the initialiser of AnyCancellable, there is no initialiser which accepts an argument, so what does 'AnyCancellable(task)' do here and is it correct?

    AnyCancellable has init(_:) that accepts a Cancellable