RxSwift Beginners Episode 2 - Bind, Subscribe, onNext, Dispose.
UITableViewDelegate
함수를 사용해 didSelectRowAt
를 커스터마이징한다.UITableViewDelegate
함수를 사용하지 않고 선택 이벤트를 구독한다. private func setTableViewModelSelectedRx() {
tableView
.rx
.modelSelected(FoodModel.self)
.subscribe(onNext: { foodModel in
guard let navDetailVC = self.storyboard?.instantiateViewController(withIdentifier: "FoodViewController") as? FoodViewController else {
return
}
navDetailVC.foodImageName = foodModel.imageName
self.navigationController?.pushViewController(navDetailVC, animated: true)
})
.disposed(by: disposeBag)
}
rx
를 통해 RxSwift 코드를 작성할 수 있고, 해당 테이블 뷰를 구성하는 모델의 선택 이벤트를 구독(subscribe
) 가능disposed
또한 여타의 RxSwift 메소드 사용 방법과 같이 메모리 관리를 위한 cancellables
에 넣기.import UIKit
import RxSwift
import RxCocoa
class ViewController: UIViewController {
let tableViewItems = [FoodModel(name: "Coke", imageName: "coke"), FoodModel(name: "Hamburger", imageName: "hamburger"), FoodModel(name: "Pizza", imageName: "pizza"), FoodModel(name: "Bulgogi", imageName: "bulgogi")]
lazy var tableViewItemsRx = Observable.just(tableViewItems)
let disposeBag = DisposeBag()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
title = "Menu"
tableView.delegate = self
setTableViewBindRx()
setTableViewModelSelectedRx()
}
private func setTableViewBindRx() {
tableViewItemsRx.bind(to: tableView
.rx
.items(cellIdentifier: "customTableViewCell", cellType: CustomTableViewCell.self)) {
(tv, tableViewItem, cell) in
cell.cellLabel.text = tableViewItem.name
cell.cellImage.image = UIImage(named: tableViewItem.imageName)
}
.disposed(by: disposeBag)
}
private func setTableViewModelSelectedRx() {
tableView
.rx
.modelSelected(FoodModel.self)
.subscribe(onNext: { foodModel in
guard let navDetailVC = self.storyboard?.instantiateViewController(withIdentifier: "FoodViewController") as? FoodViewController else {
return
}
navDetailVC.foodImageName = foodModel.imageName
self.navigationController?.pushViewController(navDetailVC, animated: true)
})
.disposed(by: disposeBag)
}
private func setTableViewItemSelectedRx() {
tableView
.rx
.itemSelected
.subscribe(onNext: { indexPath in
let foodModel = self.tableViewItems[indexPath.row]
guard let navDetailVC = self.storyboard?.instantiateViewController(withIdentifier: "FoodViewController") as? FoodViewController else {
return
}
navDetailVC.foodImageName = foodModel.imageName
self.navigationController?.pushViewController(navDetailVC, animated: true)
})
.disposed(by: disposeBag)
}
}
setTableViewBindRx()
함수setTableViewModelSelectedRx()
함수extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let navDetailVC = storyboard?.instantiateViewController(withIdentifier: "FoodViewController") as? FoodViewController else {
return
}
navDetailVC.foodImageName = tableViewItems[indexPath.row].imageName
navigationController?.pushViewController(navDetailVC, animated: true)
}
}
didSelectRowAt
함수