Skip to content

Instantly share code, notes, and snippets.

@andr3a88
Last active June 4, 2021 14:35
Show Gist options
  • Save andr3a88/bfd358ba6559474c51d4edd8c23f0c3a to your computer and use it in GitHub Desktop.
Save andr3a88/bfd358ba6559474c51d4edd8c23f0c3a to your computer and use it in GitHub Desktop.
API call with combine
import Foundation
import Combine
struct Post: Codable{
let userId: Int
let id: Int
let title: String
let body: String
}
enum APIError: Error{
case networkError(error: String)
case responseError(error: String)
case unknownError
}
let samplePost = Post(userId: 1, id: 2, title: "title", body: "")
// Create a `dataTaskPublisher`
let url = URL(string: "https://jsonplaceholder.typicode.com/posts")
let publisher = URLSession.shared.dataTaskPublisher(for: url!)
.map { $0.data }
.decode(type: Array<Post>.self, decoder: JSONDecoder())
// Subscribe to the publisher
let cancellableSink = publisher
.retry(2)
.mapError { error -> Error in
switch error {
case URLError.cannotFindHost:
return APIError.networkError(error: error.localizedDescription)
default:
return APIError.responseError(error: error.localizedDescription)
}
}
.sink(receiveCompletion: { completion in
print(String(describing: completion))
}, receiveValue: { value in
print("returned value \(value)")
})
// Try to catch error
Just(7)
.tryMap { _ in
throw APIError.unknownError
}
.catch { result in
Just(2)
}
.sink{ print($0) }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment