Skip to content

Instantly share code, notes, and snippets.

@M0rtyMerr
Last active January 23, 2019 12:47
Show Gist options
  • Save M0rtyMerr/f7c47c2b46fa72bf95adca2daa2f8136 to your computer and use it in GitHub Desktop.
Save M0rtyMerr/f7c47c2b46fa72bf95adca2daa2f8136 to your computer and use it in GitHub Desktop.
UITableViewDelegate vs RxCocoa. Rx framework can be found here - https://github.com/RxSwiftCommunity/RxDataSources
// Native way
var sections = [["Section 1": [1, 2, 3]],
["Section 2": [4, 5, 6]]]
func numberOfSections(in tableView: UITableView) -> Int {
return sections.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sections[section].count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return sections[section]
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
let item = numbers[indexPath.section][indexPath.row]
cell.textLabel?.text = item
return cell
}
// new value
sections = [...]
tableView.reloadData() // no diff comuptation
//____________________//
// RxDataSource
let sections = BehaviorRelay<[SectionModel<String, Int>]>(value:
[SectionModel(model: "Section 1", items: [1, 2, 3]),
SectionModel(model: "Section 2", items: [4, 5, 6])]
)
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, Int>>(
configureCell: { [unowned self] _, tableView, indexPath, item in
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = item
return cell
},
titleForHeaderInSection: { dataSource, sectionIndex in dataSource[sectionIndex].model }
)
sections.asDriver()
.drive(tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
// new value
sections.accept([...]) // and here you have diff computation and reloading of only needed cells
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment