简体   繁体   中英

RxSwift filter observable sequence and bind to tableview

I have tableview in my iOS App

I have initialize the table using following code

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)
}

now I have a text field and I want to filter the cList based on the text of that text field

I can print text as i press key

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)

but I am not sure how to filter cnList and update the table view

So how to do this ??

maybe like this:

First change var cnList : Observable<[CountryCode]>? to var cnList : Variable<[CountryCode]>? = Variable([]) var cnList : Variable<[CountryCode]>? = Variable([])

then:

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)
}

then:

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

I'm not sure, but it's should reload your table with new values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM