我有一个数字数组,我希望tableview
显示我在搜索栏中输入的数字。这是我的代码,我不知道我应该在(而不是) .subscribe
后面的行中写什么
let dataSource = BehaviorRelay(value: [String]())
let disposeBag = DisposeBag()
var numbers = ["1", "2", "3", "4", "5"]
override func viewDidLoad() {
super.viewDidLoad()
dataSource.accept(numbers)
searchBar.rx.text.orEmpty
.throttle(.milliseconds(2000), scheduler: MainScheduler.instance)
.filter{self.numbers.contains($0)}
.subscribe(onNext:
})
self.dataSource
.asObservable()
.bind(to: tableView.rx.items(cellIdentifier: "Cell", cellType: TableViewCell.self)) {(row, element, cell) in
cell.textLabel?.text = element
}
.disposed(by: disposeBag)
也许是因为其他原因而不起作用,不管怎样,谢谢你的帮助
发布于 2021-05-25 17:48:42
更新:
您希望将反应性代码视为因果链。有些副作用会引起其他副作用。当然,在因果之间,您有业务逻辑。
首先,请注意,这一主题没有必要。在Rx简介一书中,我们了解到:
受试者提供了一种方便的方式,在Rx周围戳,但他们不推荐日常使用。
既然我们在想“因果”..。我们想达到的效果是什么?这将是表视图的输出,其中:
这是三个原因和逻辑定义的原因如何影响的效果。
final class Example: UIViewController {
var searchBar: UISearchBar!
var addButton: UIButton!
var deleteButton: UIButton!
var tableView: UITableView!
let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
enum Input {
case add
case delete
}
let initial = ["1", "2", "3", "4", "5"] // this is what we start with
Observable.merge(
addButton.rx.tap.map { Input.add }, // flag addButton taps for adding a number
deleteButton.rx.tap.map { Input.delete } // flag deleteButton taps for deleting a number
)
.scan(into: initial) { state, input in // setup a state machine that:
switch input {
case .add:
state.append("\(state.count + 1)") // adds a number when the add event happens
case .delete:
state.removeLast() // removes the last number when a delete event happens
}
}
.withLatestFrom(searchBar.rx.text) { list, text in
list.filter { $0 == text } // here we filter the list based on the value in the search bar
}
.startWith(initial) // show the initial values at start
.bind(to: tableView.rx.items(cellIdentifier: "Cell", cellType: UITableViewCell.self)) { _, element, cell in
cell.textLabel?.text = element
}
.disposed(by: disposeBag)
}
}
您可能想要使过滤器或多或少比我上面的复杂。要使上述可测试性,只需将闭包移出到单独的函数中,这样就可以独立测试它们。
https://stackoverflow.com/questions/67692248
复制相似问题