Skip to content

Instantly share code, notes, and snippets.

@kashiftriffort
Last active April 20, 2020 12:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kashiftriffort/f3bbbb2cc874af0a8e91ebe14b5d25ba to your computer and use it in GitHub Desktop.
Save kashiftriffort/f3bbbb2cc874af0a8e91ebe14b5d25ba to your computer and use it in GitHub Desktop.
Combine Example in Swift
enum HTTPError: LocalizedError {
case statusCode
}
enum RequestError: Error {
case sessionError(error: Error)
}
struct Post: Codable {
let id: Int
let title: String
let body: String
let userId: Int
}
struct ToDo: Codable {
let id: Int
let title: String
let completed: Bool
let userId: Int
}
var cancellable: AnyCancellable?
func combineWithOutError() {
let dummyURL = URL(string: "https://jsonplaceholder.typicode.com/posts")
cancellable = URLSession.shared.dataTaskPublisher(for: dummyURL!)
.map { $0.data }
.decode(type: [Post].self, decoder: JSONDecoder())
.replaceError(with: [])
.eraseToAnyPublisher()
.sink(receiveValue: { posts in
print(posts.map { $0.id })
})
}
func combineWithError() {
let dummyURL = URL(string: "https://jsonplaceholder.typicode.com/posts")
cancellable = URLSession.shared.dataTaskPublisher(for: dummyURL!)
.tryMap { output in
guard let response = output.response as? HTTPURLResponse, response.statusCode == 200 else {
throw HTTPError.statusCode
}
print(response.statusCode)
return output.data
}
.decode(type: [Post].self, decoder: JSONDecoder())
.eraseToAnyPublisher()
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
break
case .failure(let error):
print(error.localizedDescription)
}
}, receiveValue: { posts in
print("Post Title\(posts.map({ $0.title }))")
})
}
func combineMultipleRequest() {
let url1 = URL(string: "https://jsonplaceholder.typicode.com/posts")!
let url2 = URL(string: "https://jsonplaceholder.typicode.com/todos")!
let postPublisher = URLSession.shared.dataTaskPublisher(for: url1)
.map{ $0.data }
.decode(type: [Post].self, decoder: JSONDecoder())
let todoPublisher = URLSession.shared.dataTaskPublisher(for: url2)
.map{ $0.data }
.decode(type: [ToDo].self, decoder: JSONDecoder())
cancellable = Publishers.Zip(postPublisher, todoPublisher)
.eraseToAnyPublisher()
.catch { _ in
Just(([], []))
}
.sink(receiveValue: { posts, todos in
print(posts.count)
print(todos.count)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment