如何使用 RXSwift 为单个 tableview 单元格重新加载数据

How to reload data for a single tableview cell using RXSwift

我有一个表视图,其单元格绑定到 listItemRelay,如下所示:

viewModel?.listItemsRelay
        .subscribeOn(ConcurrentDispatchQueueScheduler(qos: .userInitiated))
        .share()
        .observeOn(MainScheduler.instance)
        .bind(to: cardTableView.rx.items(cellIdentifier: CardCell.identifier, cellType: CardCell.self))({ [weak self] index, listItem, cell in
            self?.update(cell: cell, at: index, with: listItem)
        })
        .disposed(by: disposeBag)

现在,如果其中一个 listItem 发生了变化,我只想更新那个单元格。我在这里该怎么做,我是 RXSwift 的新手。

简单的答案是使用 RxDataSources,它只会更新实际发生变化的单元格。

自主开发的解决方案是使用细胞观察到的不同可观察值来确定它们的内容应该是什么:

viewModel?.listItemIdsRelay
    .observe(on: MainScheduler.instance)
    .bind(to: cardTableView.rx.items(cellIdentifier: CardCell.identifier, cellType: CardCell.self))({ [unowned self] index, id, cell in
        self.viewModel!.listItemsRelay
            .compactMap { [=10=][id] }
            .bind { listItem in
                self.update(cell: cell, at: index, with: listItem)
            }
            .disposed(by: cell.disposeBag)
    })
    .disposed(by: disposeBag)

listItemIdsRelay 告诉 tableView 要显示哪些列表项,并且仅在从数组中添加或删除项时更新。细胞观察 listItemsRelay 并在它们观察的列表项更新时更新。