Subscription to a UIButton.rx.tap located in UITableViewCell within UITableViewDataSource

邮差的信 提交于 2019-12-03 20:55:09

Another solution (which doesn't require an additional library or calling Disposable.dispose()) is to have a DisposeBag in the cell and re-create it in prepareForReuse, as suggested in this GitHub issue:

//in the cell 

private(set) var disposeBag = DisposeBag()

override func prepareForReuse() {
   super.prepareForReuse()
   disposeBag = DisposeBag()
}


//in the data source
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! DiaryItemCell

cell.commentButton.rx_tap
            .subscribeNext{

            }.addDisposableTo(cell.disposeBag)

return cell

It will also work if you have more buttons (or other Observables which you want to subscribe to) in your cell. You won't have to create a new Disposable in the cell itself for each of them.

You can use Cell-Rx pod form correct using reactive subscriptions in UITableViewCell. For your case you can use rx_reusableDisposeBag, it will dispose your subscriptions correct.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!