[Part-3] Model View ViewModel(MVVM) pattern using RxSwift 2022 | RxDataSources with CRUD Operation
RxDataSources
를 통한 테이블 뷰 UI 구현RxDataSources
을 통한 테이블 뷰 바인딩 private func bind() {
tableView
.rx
.setDelegate(self)
.disposed(by: disposeBag)
let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressed(recognizer:)))
tableView.addGestureRecognizer(longPressGesture)
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, UserModel>> { _, tableView, indexPath, item in
guard let cell = tableView.dequeueReusableCell(withIdentifier: UserTableViewCell.identifier, for: indexPath) as? UserTableViewCell else { fatalError() }
cell.configure(with: item)
return cell
} titleForHeaderInSection: { dataSource, sectionIndex in
return dataSource[sectionIndex].model
}
viewModel
.users
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
tableView
.rx
.itemDeleted
.subscribe { [weak self] indexPath in
self?.viewModel.delete(indexPath: indexPath)
}
.disposed(by: disposeBag)
}
bind
의 to
대상이 tableView.rx.items
를 커스텀 데이터 소스(RxTableViewSectionedReloadDataSource
)를 통해 이니셜라이즈된 것으로 변경 let users: BehaviorSubject = .init(value: [SectionModel(model: "", items: [UserModel]())])
RxDataSources
가 제공하는 SectionModel
을 통해 구현func edit(title: String, indexPath: IndexPath) {
guard var sections = try? users.value() else { return }
var currentSection = sections[indexPath.section]
currentSection.items[indexPath.row].title = title
sections[indexPath.section] = currentSection
users.on(.next(sections))
}
Diffable DataSource
와 UI를 그리는 로직이 비슷한 것처럼 보인다.