使用過程中爬坑記錄一下
RxSwift 計數(shù)問題
兩個頁面,A,B.需要實(shí)現(xiàn)B頁面給A頁面?zhèn)髦?,可以通過序列實(shí)現(xiàn):
B 的VC:
// 內(nèi)部序列響應(yīng),不被外界影響
fileprivate var mySubject = PublishSubject<Any>()
var publicOB : Observable<Any>{
return mySubject.asObservable()
}
- 對外暴露publicOB,以便訂閱信息
- mySubject序列響應(yīng),內(nèi)部事件發(fā)送
- 內(nèi)外區(qū)分,達(dá)到干凈的效果
A VC中:
let vc = LGDetialViewController()
vc.publicOB
.subscribe(onNext: { (item) in
print("訂閱到 \(item)")
})
.disposed(by: vc.disposeBag)
self.navigationController?.pushViewController(vc, animated: true)
- 這里注意需要使用vc.disposeBag
cell復(fù)用導(dǎo)致序列重復(fù)訂閱響應(yīng)
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! LGTableViewCell
cell.button.rx.tap
.subscribe(onNext: { () in
print("點(diǎn)擊了 \(indexPath)")
})
.disposed(by: bag)
return cell
}
- 這一段代碼乍一看也是沒有什么問題的,包括你不滑動屏幕也不會產(chǎn)生問題
- 只要你一劃動屏幕,因?yàn)槲覀兊?code>cell的重用機(jī)制,會導(dǎo)致
cell.button.rx.tap的訂閱也會重復(fù)訂閱響應(yīng),顯然不是我們正常
開發(fā)中想見到的樣子
點(diǎn)擊了 [0, 0]
********************
點(diǎn)擊了 [0, 1]
********************
點(diǎn)擊了 [0, 2]
********************
點(diǎn)擊了 [0, 1]
點(diǎn)擊了 [0, 21]
********************
點(diǎn)擊了 [0, 3]
點(diǎn)擊了 [0, 23]
********************
點(diǎn)擊了 [0, 29]
點(diǎn)擊了 [0, 49]
點(diǎn)擊了 [0, 69]
********************
** 解決思路
- 思路一: 把主動銷毀的能力收回,銷毀垃圾袋交給我們的cell.disposeBag,在我們重用響應(yīng)的時候,及時銷毀,重置!
// 外界訂閱處理
cell.button.rx.tap
.subscribe(onNext: { () in
print("點(diǎn)擊了 \(indexPath)")
})
.disposed(by: cell.disposeBag)
// cell內(nèi)部處理
override func prepareForReuse() {
super.prepareForReuse()
// 銷毀垃圾袋重置
disposeBag = DisposeBag()
}
銷毀垃圾袋交給cell自身
在prepareForReuse 響應(yīng)的時候,銷毀垃圾袋重置
效果很明顯,問題得到了解決!