mapbox / mapbox-directions-swift

Traffic-aware directions and map matching in Swift on iOS, macOS, tvOS, watchOS, and Linux
https://www.mapbox.com/navigation/
ISC License
183 stars 90 forks source link

Directions methods should return some kind of Cancellable protocol instead of URLSessionDataTask #465

Open SebastianOsinski opened 4 years ago

SebastianOsinski commented 4 years ago

Right now all methods in Directions class return URLSessionDataTask instance directly. This makes subclassing Directions harder, as it leaks internal implementation of it (i.e. it uses URLSession underneath). As far as I noticed, returned tasks are only used for cancelling them, so it is possible to just introduce Cancellable protocol in form of:

public protocol Cancellable {
    func cancel()
}

with extension for URLSessionDataTask:

extension URLSessionDataTask: Cancellable {}

and declare all methods to return it instead of URLSessionDataTask. This will allow to make subclasses of Directions (e.g. one using other web service than Mapbox's one or some offline solution) without being tied to URLSession.

1ec5 commented 4 years ago

This will allow to make subclasses of Directions (e.g. one using other web service than Mapbox's one or some offline solution) without being tied to URLSession.

As a workaround for now, you can call that subclass’s url(forCalculating:) or urlRequest(forCalculating:), pass the return value into your third-party networking library, and transform the resulting data into a RouteResponse using JSONDecoder. Historically, url(forCalculating:) was this library’s answer for using a third-party library, but a protocol would make the library more flexible.