我想在Rxswift中使用Variable
来使caseResults搜索不同的结果,使用不同的boxId,例如boxId == 1
获取结果,boxId == 2
获取另一个结果
class MainViewModel {
let cases: Driver<[CaseItemViewModel]>
let index = Variable<Int>(1)
init() {
let caseResults = realm.objects(RMCase.self)
.filter("boxId == \(index.value)")
.sorted(byKeyPath: "id", ascending: true)
self.cases = Observable.collection(from: caseResults)
.asDriverOnErrorJustComplete()
.map { results in results.map { CaseItemViewModel(with: $0) }}
}
}
class CaseItemViewModel {
let cased: RMCase
let id: Int
let boxId: Int
let name: String
init(with cased: RMCase) {
self.cased = cased
self.id = cased.id
self.boxId = cased.boxId
self.name = cased.name
}
}
在ViewController中
viewModel.boxs
.drive(tableView.rx.items(cellIdentifier: CellId.main.rawValue, cellType: MainTableViewCell.self)) { [weak self] row, item, cell in
guard let strongSelf = self else { return }
cell.setup(with: item)
// drive collectionView into tableViewCell
if let collectionView = cell.collectionView {
strongSelf.viewModel.cases.asObservable()
.bind(to:collectionView.rx.items(cellIdentifier: "testcell", cellType: MainCollectionViewCell.self)) { _row, _item, _cell in
_cell.setup(with: _item)
}
.disposed(by: cell.disposeBag)
}
}.disposed(by: disposeBag)
答案 0 :(得分:2)
首先,不推荐使用Variable
,而是使用BehaviorRelay
或BehaviorSubject
。
将cases
更改为BehaviorRelay
,这样您就不必在init
中对其进行初始化,然后观察index
属性,并在每次更改时将新结果绑定到cases
喜欢这样:
let cases = BehaviorRelay<[CaseItemViewModel]>(value: [])
let index = BehaviorRelay<Int>(value: 1)
init() {
index
.flatMap { index -> Observable<Results<RMCase>> in
let caseResult = realm.objects(RMCase.self)
.filter("boxId == \(index)")
.sorted(byKeyPath: "id", ascending: true)
return Observable.collection(from: caseResult)
}
.map { results in results.map { CaseItemViewModel(with: $0) }}
.bind(to: cases)
.disposed(by: disposeBag)
}
在cases
中,您现在总是拥有CaseItemViewModel
数组,并且每次index
更改时都会填充新值。