![](/img/trans.png)
[英]Build error when binding a `RxTableViewSectionedAnimatedDataSource` to a UITableView
[英]Why UITableViewCell does not bind to cellWiewModel when I use RxTableViewSectionedAnimatedDataSource?
當我將 MVVM 模式與 RxSwift 一起使用時, UITableViewCell
出現了一些奇怪的問題。 我無法描述它,但我會盡力解釋。
假設我們有簡單的 UITableViewCell
class MyTableViewCell: UITableViewCell {
var disposeBag = DisposeBag()
override func prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
}
func bind(to viewModel: MyCellViewModel) {
viewModel.randomValue.asDriver()
.drive(onNext: { [weak self] value in
guard let self = self else { return}
print(value) // WHEN TWO CELLS I GET NEW VALUES JUST IN ONE OF THEM
})
.disposed(by: disposeBag)
}
使用帶有簡單計時器的 ViewModel。
class MyCellViewModel: NSObject {
let randomValue = PublishSubject<Int>()
init() {
Observable<Int>.timer(.seconds(1), period: .seconds(1), scheduler: SerialDispatchQueueScheduler(qos: .userInteractive))
.map { _ in Int.random()}
.do(onNext: {
print($0) // WORK PERFECT FOR BOTH
})
.bind(to: randomValue)
.disposed(by: rx.disposeBag)
}
}
我還使用 RxDataSources 來填充我的 tableView。
private func makeDataSource() -> RxTableViewSectionedAnimatedDataSource<Section> {
RxTableViewSectionedAnimatedDataSource<Section>(configureCell: { _, tableView, indexPath, item in
switch item {
case let .myItem(cellViewModel):
let cell = tableView.dequeueReusableCell(with: MyTableViewCell.self, for: indexPath)
cell.bind(to: cellViewModel)
return cell
}
})
}
問題是,當我有兩個單元格時,我在其中一個單元格中獲得了新值,而在另一個單元格中卻沒有。
注意方法bind(to viewModel
但是當我將RxTableViewSectionedAnimatedDataSource
更改為RxTableViewSectionedReloadDataSource
時一切正常。
如何讓它與RxTableViewSectionedAnimatedDataSource
一起工作? 我了解它們之間的區別,但在這種情況下,我不知道這有何影響?
我還檢查了 memory 圖,只看到了兩個單元格實例和兩個 cellViewModels 實例。 所以我希望沒有泄漏。
謝謝你的幫助!
您實施ItemMode.==
不正確。 它實際上並不檢查是否相等,它只檢查身份。 刪除 function 並讓編譯器為您生成正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.