Skip to content

Instantly share code, notes, and snippets.

@atrinh0
Last active April 25, 2021 17:21
Show Gist options
  • Save atrinh0/f0acbaf8c41b9df99468600570d4dae1 to your computer and use it in GitHub Desktop.
Save atrinh0/f0acbaf8c41b9df99468600570d4dae1 to your computer and use it in GitHub Desktop.
Combine walkthrough
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
@atrinh0
Copy link
Author

atrinh0 commented Apr 25, 2021

Screenshot 2021-04-25 at 18 21 09

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment