Last active
April 25, 2021 17:21
-
-
Save atrinh0/f0acbaf8c41b9df99468600570d4dae1 to your computer and use it in GitHub Desktop.
Combine walkthrough
This file contains 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 Foundation | |
import Combine | |
import UIKit | |
import PlaygroundSupport | |
struct Image: Decodable { | |
let url: String | |
} | |
let stackView = UIStackView(frame: CGRect(x: 0, y: 0, width: 200, height: 600)) | |
stackView.axis = .vertical | |
let images = URLSession.shared.dataTaskPublisher(for: URL(string: "https://atrinh.com/dev/images.json")!) | |
.map(\.data) | |
.decode(type: [Image].self, decoder: JSONDecoder()) | |
.flatMap { $0.publisher } | |
.compactMap { URL(string: $0.url) } | |
.flatMap { url in | |
return URLSession.shared.dataTaskPublisher(for: url) | |
.mapError { $0 as Error } | |
.map { response in | |
UIImage(data: response.data) | |
} | |
} | |
.receive(on: DispatchQueue.main) | |
.sink(receiveCompletion: { _ in }, | |
receiveValue: { image in | |
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) | |
imageView.image = image | |
stackView.addArrangedSubview(imageView) | |
}) | |
PlaygroundPage.current.liveView = stackView |
Author
atrinh0
commented
Apr 25, 2021
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment