使用RxSwift使用变量id过滤领域结果

时间:2018-03-24 05:53:51

标签: realm rx-swift

我想在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)

1 个答案:

答案 0 :(得分:2)

首先,不推荐使用Variable,而是使用BehaviorRelayBehaviorSubject

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更改时都会填充新值。