我为 1 UIButton 订阅了 2 次:
- 首次订阅,每次点击更新 UI
- 第二次订阅,用于在累积点击后每 1 秒更新一次 Web Service 上的值。
代码:
class ProductionSize {
var id : Int?
var size: Int = 0
var name: String = ""
}
class ProductionCell: UICollectionViewCell {
var rxBag = DisposeBag()
// this will be set in the (cellForItemAt indexPath: IndexPath) of collection view
var productionSize: ProductionSize? {
didSet {
showProductionSize()
prepareButton()
}
}
func showProductionSize() {
// ... code for showing ProductionSize in labels
}
func prepareButton() {
// This for subscribing for every click for displaying purpose
btn_increase.rx.tap
.subscribe(){event in
self.increaseClicked()
}
.addDisposableTo(rxBag)
// this for subscribing for sending webservice request after 1 second of clicking the button (so that if user click it quickly i send only last request)
btn_increase.rx.tap
.debounce(1.0, scheduler: MainScheduler.instance)
.subscribe(){ event in self.updateOnWS() }
.addDisposableTo(rxBag)
}
func increaseClicked() {
productionSize.size = productionSize.size + 1
showProductionSize()
}
func updateOnWS() {
// code for updating on webservice with Moya, RxSwift and Alamofire§
}
// when scrolling it gets called to dispose subscribtions
override func prepareForReuse() {
rxBag = DisposeBag()
}
}
问题:
由于处置发生在prepareForReuse()
,如果我多次单击该按钮并立即滚动,则 Web 服务调用将被处置且未更新。
我尝试过的:
添加
addDisposableTo(vc?.rx_disposableBag)
到父 ViewController DisposableBag。问题是,订阅的累积和每次点击都会被
updateWS()
调用多次,每次滚动都订阅了并且从未处理过。我试图从
prepareForReuse()
.问题是,按钮的订阅再次被重复和累积,并且每次点击都会调用许多 Web 服务调用。
问题:
我怎样才能让debounce
订阅被调用到最后并且从不重复多个订阅(在addDisposableTo
viewController Bag 的情况下)?