Example (you can run this example code in a project or in a playground, but it has no effect in shell mode, which meand don’t use `swift a.swift`
struct Postman: Codable {
let valid: Bool
}
enum MyError: Error {
case invalidServerResponse
}
let url = URL(string: "https://postman-echo.com/time/valid?timestamp=2016-10-10")!
let cancellable = URLSession.shared.dataTaskPublisher(for: url)
.tryMap { data, response -> Data in
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw MyError.invalidServerResponse
}
return data
}
.decode(type: Postman.self, decoder: JSONDecoder())
.sink(receiveCompletion: { completion in
print(".sink() received the completion", String(describing: completion))
switch completion {
case .finished:
break
case .failure(let error):
print("received error: ", error)
}
}, receiveValue: { value in
print(".sink() received \(value)")
})