RxSwift 过滤可观察序列并绑定到 tableview

RxSwift filter observable sequence and bind to tableview

我的 iOS 应用程序中有 table视图

我已经使用下面的代码 table 初始化

var cnList : Observable<[CountryCode]>?
override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    cnList = readJson()
        cnList?.bindTo(cTableView.rx.items(cellIdentifier: "country_code_cell")) {
            _, countryCode, cell in
            if let countryCodeCell = cell as? CountryCodeTableViewCell {
                countryCodeCell.cNameLabel.text = countryCode.name
                countryCodeCell.cCodeLabel.text = countryCode.dial_code!
            }
        }.addDisposableTo(disposeBag)
}

现在我有一个文本字段,我想根据该文本字段的文本过滤 cList

我可以在按键时打印文本

searchTextField.rx.text.asObservable().subscribe(onNext: {
            text in
            if text != nil && text != "" {
                // need to filter cnList and update tableview here i think but how ??
            }
        }).addDisposableTo(disposeBag)

但我不确定如何过滤 cnList 和更新 table view

那么怎么做呢??

可能是这样的:

先把var cnList : Observable<[CountryCode]>?改成var cnList : Variable<[CountryCode]>? = Variable([])

然后:

override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
    cnList.value = readJson()
        cnList?.asObservable().bindTo(cTableView.rx.items(cellIdentifier: "country_code_cell")) {
            _, countryCode, cell in
            if let countryCodeCell = cell as? CountryCodeTableViewCell {
                countryCodeCell.cNameLabel.text = countryCode.name
                countryCodeCell.cCodeLabel.text = countryCode.dial_code!
            }
        }.addDisposableTo(disposeBag)
}

然后:

searchTextField.rx.text.asObservable().subscribe(onNext: {
            text in
            if text != nil && text != "" {
               self.cnList.value = self.cnList.value.filter({//some logic})
            }
        }).addDisposableTo(disposeBag)

我不确定,但它应该用新值重新加载您的 table。