-
RxSwift basic test (count 1씩 올리기)Swift/RxSwift 2022. 9. 28. 23:07
with RxSwift
import UIKit import Then import RxSwift import RxCocoa class ViewController: UIViewController { private var count = BehaviorSubject(value: 0) private let bag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() setupBindings() setupLayout() } private func setupBindings() { btn.rx.tap .subscribe(onNext: { [weak self] _ in guard let self = self else { return } print("btn tapped!") do { let value = try self.count.value() self.count.on(.next(value + 1)) } catch let error { print(error.localizedDescription) } }).disposed(by: bag) count .subscribe(onNext: { [weak self] num in guard let self = self else { return } DispatchQueue.main.async { self.countLabel.text = String(num) } }) .disposed(by: bag) } private let btn = UIButton().then { $0.backgroundColor = .gray $0.setTitle("Tap Me", for: .normal) } private let countLabel = UILabel().then { $0.textColor = .gray } }
Vanila Swift
import UIKit import Then import RxSwift import RxCocoa class ViewController: UIViewController { private var count = 0 private let bag = DisposeBag() override func viewDidLoad() { super.viewDidLoad() setupAddTargets() setupLayout() } private func setupLayout() { [countLabel, btn].forEach { self.view.addSubview($0)} countLabel.snp.makeConstraints { make in make.center.equalToSuperview() make.height.width.equalTo(40) } btn.snp.makeConstraints { make in make.top.equalTo(countLabel.snp.bottom).offset(100) make.width.lessThanOrEqualTo(view.snp.width).offset(-30) make.height.equalTo(40) } } private func setupAddTargets() { btn.addTarget(self, action: #selector(btnTapped), for: .touchUpInside) } @objc func btnTapped() { count += 1 countLabel.text = String(count) } private let btn = UIButton().then { $0.backgroundColor = .gray $0.setTitle("Tap Me", for: .normal) } private let countLabel = UILabel().then { $0.textColor = .gray } }
'Swift > RxSwift' 카테고리의 다른 글
UITableView (with RxSwift) (2) 2022.09.30 Login Validation (simple..) RxSwift 구현 (0) 2022.09.29 RxSwift - API Call (0) 2022.07.26 RxSwift Merge 이용해서 Event 묶기 (0) 2022.07.20 Difference between bindTo and drive ( RxSwift) (0) 2022.03.30