I am new here about RxSwift, In my case, I want to use UserDefaults with RxSwift to simplify my code, so I did this following code
my question is, when I clicked a cell, but the subscribe method submit twice? so what should I do to fix it? thx a lot!
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.
}
}
distinctUntilChanged()
– Galloot