Last active
March 27, 2021 13:06
-
-
Save gtokman/5c039b74b118437cf7214d3c97b0143e to your computer and use it in GitHub Desktop.
URLSession + Combine
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 characters
| import UIKit | |
| import Combine | |
| import PlaygroundSupport | |
| let label = UILabel(frame: .init(origin: .zero, size: CGSize(width: 100, height: 100))) | |
| let url = URL(string: "https://api.mocki.io/v1/aebff128")! | |
| var cancellables = Set<AnyCancellable>() | |
| URLSession | |
| .shared | |
| .dataTaskPublisher(for: url) // 1 | |
| .map(\.data) // 2 | |
| .decode(type: [String: [String]].self, decoder: JSONDecoder()) // 3 | |
| .compactMap(\.["results"]) // 4 | |
| .replaceError(with: []) // 5 | |
| .map { $0.joined(separator: " ") } | |
| .receive(on: DispatchQueue.main) // 6 | |
| .assign(to: \.text, on: label) // 7 | |
| .store(in: &cancellables) // 8 | |
| PlaygroundSupport.PlaygroundPage.current.liveView = label |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment