Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save karigrooms/8b6db45ec9563889167d9f0f8928c1f9 to your computer and use it in GitHub Desktop.
Save karigrooms/8b6db45ec9563889167d9f0f8928c1f9 to your computer and use it in GitHub Desktop.
Blog: ObservableObjects and Protocols - ObservableObject in UIKit
// Copyright 2021 Expedia, Inc.
// SPDX-License-Identifier: Apache-2.0
import Combine
import UIKit
class DemoController: UIViewController {
private let pricing: PricingProvider
private var subscriptions = Set<AnyCancellable>()
private lazy var stackView: UIStackView = {
let view = UIStackView()
view.alignment = .center
view.axis = .vertical
view.spacing = 8
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
private lazy var priceLabel: UILabel = {
let label = UILabel()
label.text = "Price not available"
return label
}()
private lazy var fetchPriceButton: UIButton = {
let button = UIButton()
button.backgroundColor = UIColor(named: "ActionColor")
button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 24, bottom: 0, right: 24)
button.layer.cornerRadius = 22;
button.setTitle("Fetch price", for: .normal)
button.addTarget(self, action: #selector(onTap), for: .touchUpInside)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
stackView.addArrangedSubview(priceLabel)
stackView.addArrangedSubview(fetchPriceButton)
view.addSubview(stackView)
NSLayoutConstraint.activate([
fetchPriceButton.heightAnchor.constraint(equalToConstant: 44),
stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor)
])
subscribe()
}
init(pricing: PricingProvider) {
self.pricing = pricing
let bundle = Bundle(for: type(of: self))
super.init(nibName: nil, bundle: bundle)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func onTap() {
pricing.fetch()
}
private func subscribe() {
pricing.$price.sink { newPrice in
guard let price = newPrice else {
self.priceLabel.text = "Price not available"
return
}
self.priceLabel.text = "\(price.amount) \(price.description)"
}
.store(in: &subscriptions)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment