Last active
June 4, 2021 14:35
-
-
Save andr3a88/bfd358ba6559474c51d4edd8c23f0c3a to your computer and use it in GitHub Desktop.
Revisions
-
andr3a88 revised this gist
Jun 4, 2021 . 1 changed file with 29 additions and 1 deletion.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -7,16 +7,44 @@ struct Post: Codable{ 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) } -
andr3a88 created this gist
Jun 4, 2021 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,22 @@ import Foundation import Combine struct Post: Codable{ let userId: Int let id: Int let title: String let body: String } let samplePost = Post(userId: 1, id: 2, title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body: "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto") 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()) let cancellableSink = publisher .sink(receiveCompletion: { completion in print(String(describing: completion)) }, receiveValue: { value in print("returned value \(value)") })