RxSwift <11>—— 爬坑

使用過程中爬坑記錄一下
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)的時候,銷毀垃圾袋重置

  • 效果很明顯,問題得到了解決!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容