Skip to content

Commit

Permalink
Merge pull request #11 from etempls/endpoint-publisher
Browse files Browse the repository at this point in the history
Add Endpoint publisher, powered by Combine
  • Loading branch information
chriseidhof authored Dec 26, 2019
2 parents bfb456a + af2d6b7 commit 6676e02
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions Sources/TinyNetworking/Endpoint.swift
Original file line number Diff line number Diff line change
Expand Up @@ -240,3 +240,31 @@ extension URLSession {
}
}

#if canImport(Combine)
import Combine

@available(iOS 13, macOS 10.15, watchOS 6, tvOS 13, *)
extension URLSession {
/// Returns a publisher that wraps a URL session data task for a given Endpoint.
///
/// - Parameters:
/// - e: The endpoint.
/// - Returns: The publisher of a dataTask.
public func load<A>(_ e: Endpoint<A>) -> AnyPublisher<A, Error> {
let r = e.request
return dataTaskPublisher(for: r)
.tryMap { data, resp in
guard let h = resp as? HTTPURLResponse else {
throw UnknownError()
}

guard e.expectedStatusCode(h.statusCode) else {
throw WrongStatusCodeError(statusCode: h.statusCode, response: h)
}

return try e.parse(data, resp).get()
}
.eraseToAnyPublisher()
}
}
#endif

0 comments on commit 6676e02

Please sign in to comment.