我是RxSwift的新手,在我的例子中,我想使用UserDefaults和RxSwift来简化我的代码,所以我做了以下代码
我的问题是,当我单击一个单元格时,subscribe方法提交了两次?那么我应该做些什么来修复它呢?非常感谢!
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
class ViewController: UIViewController {
let disposeBag = DisposeBag()
@IBOutlet weak var tableView: UITableView! {
didSet {
tableView.register(UITableViewCell.self, forCellReuseIdentifier: String(describing: UITableViewCell.self))
tableView.rx
.itemSelected
.subscribe { (indexPath) in
UserDefaults.standard.set("\(indexPath)", forKey: "key")
}
.disposed(by: disposeBag)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
UserDefaults.standard.rx
.observe(String.self, "key")
// .debug()
.subscribe(onNext: { (value) in
if let value = value {
print(value)
}
})
.disposed(by: disposeBag)
let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, String>>()
dataSource.configureCell = { (dataSource, tableView, indexPath, item) in
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: UITableViewCell.self), for: indexPath)
cell.textLabel?.text = item
return cell
}
Observable.just([SectionModel(model: "", items: (0..<5).map({ "\($0)" }))])
.bindTo(tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}发布于 2017-10-31 18:58:03
这确实是一种bug,我建议使用distinctUntilChanged()。
按照@wisper的建议使用debounce()可能在大多数情况下都有效,但这是危险的,因为您依赖于由observable发出的事件的速度。
发布于 2017-03-19 19:01:57
iOS错误,v10.2
UserDefaults.standard.rx
.observe(String.self, "key")
+ .debounce(0.1, scheduler: MainScheduler.asyncInstance)
...发布于 2019-04-10 15:26:23
您可以尝试使用take(n),其中'n‘是来自可观察序列的连续元素的数量。
tableView.rx
.itemSelected
.take(1)
.subscribe { (indexPath) in
UserDefaults.standard.set("\(indexPath)", forKey: "key")
}
.disposed(by: disposeBag)https://stackoverflow.com/questions/42877504
复制相似问题