我正在使用RxSwift和RxRealm以及RxRealmDataSources。我的领域对象绑定到表视图。我正试图找到一种方法来根据搜索栏中输入的查询来过滤它。你有没有人这样做过吗?
class ItemsViewController: UITableViewController {
let bag = DisposeBag()
let searchController = UISearchController(searchResultsController: nil)
let search = BehaviorSubject(value: "")
override func viewDidLoad() {
super.viewDidLoad()
searchController.searchResultsUpdater = self
definesPresentationContext = true
tableView.tableHeaderView = searchController.searchBar
bindTableView()
}
func bindTableView() {
let dataSource = RxTableViewRealmDataSource<Item>(cellIdentifier: "itemCell", cellType: UITableViewCell.self) { cell, ip, item in
cell.textLabel?.text = item.uuid
}
Observable.changeset(from: DataStore.sharedInstance.getObjects(Item.self))
.bind(to: tableView.rx.realmChanges(dataSource))
.addDisposableTo(bag)
}
}
extension ItemsViewController: UISearchResultsUpdating {
public func updateSearchResults(for searchController: UISearchController) {
search.onNext(searchController.searchBar.text ?? "")
}
}
答案 0 :(得分:0)
最简单的方法是:
func bindTableView() {
let dataSource = RxTableViewRealmDataSource<Item>(cellIdentifier: "itemCell", cellType: UITableViewCell.self) { cell, ip, item in
cell.textLabel?.text = item.uuid
}
search.asObservable()
.map { text in DataStore.sharedInstance.getObjects(Item.self).filter("someProperty == %@", text) }
.flatMap { results in Observable.changeset(from: results) }
.bind(to: tableView.rx.realmChanges(dataSource))
.addDisposableTo(bag)
}
答案 1 :(得分:0)
https://stackoverflow.com/a/46364131/7694178中的问题可能是多个绑定。试试这个:
let changeset = Observable.changeset(from: DataStore.sharedInstance.getObjects(Item.self))
Observable.combineLatest(changeset, search.asObservable()) { changeset, string in
return (changeset.0.filter("someProperty == %@", string), changeset.1)
}
.bind(to: tableView.rx.realmChanges(dataSource))
.disposed(by: bag)