For context, I am using swift & MVVM architecture to manage a list of data, and a table view that displays it. Reactive patterns (RxSwift or Combine) work well for letting me reload my entire table view when the view model's list data changes.
ViewModel (using RxSwift):
var tableData = BehaviorRelay<[String]>(value: ["First Item", "Second Item"])
ViewController:
var tableView = UITableView()
var disposeBag = DisposeBag()
var viewModel = ViewModel()
init() {
...
viewModel.tableData.subscribe(onNext: { _ in
self.tableView.reloadData()
}).disposed(by: disposeBag)
}
But what if only one item has been inserted or deleted from tableData
? In this case, I don't want to call tableView.reloadData()
, instead I'd like to use tableView.insertRows(at: <[IndexPath]>, with: <UITableView.RowAnimation>)
or tableView.deleteRows(at: <[IndexPath]>, with: <UITableView.RowAnimation>)
. In order to do this, I need to be able to subscribe to the index paths that have been inserted or removed, instead of the list data as a whole. Does any one know what the most efficient way to do this?
Use UITableViewDiffableDataSource. It takes care of this automatically (reactively) for you.