-2

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.

pumpum
  • 555
  • 3
  • 5
  • 18
  • 1
    @bestiosdeveloper no, [Cancellable](https://developer.apple.com/documentation/combine/cancellable) is part of the Combine framework – Joakim Danielson Apr 13 '21 at 12:28
  • I guess the purpose of making URLSessionDataTask conform to Cancellable is so that the function can return a value that can be cancelled using AnyCancellable since this class implements cancel(). Point 3 is incorrect, see https://developer.apple.com/documentation/combine/anycancellable – Joakim Danielson Apr 13 '21 at 12:32

1 Answers1

1
  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

New Dev
  • 48,427
  • 12
  • 87
  • 129
  • Hi @New Dev, thank you for the explanation. But I am not quite sure what do you mean by: 'and store(in:) is implemented as an extension on Cancellable providing a default implementation'. I checked the source code of 'Cancellable' and I did not see that store(in:) is implemented. – pumpum Apr 13 '21 at 14:00
  • Where have you checked the source code of `Cancellable`? But also, with protocol extensions in Swift, anyone anywhere could provide a [default implementation](https://docs.swift.org/swift-book/LanguageGuide/Protocols.html#ID529). – New Dev Apr 13 '21 at 16:28