简体   繁体   English

RxSwift Textfield防反跳订阅未调用

[英]RxSwift Textfield debounce subscribe is not calling

Changes after 0.3 seconds when user stop typing should be displayed in label but subscribe onNext is not calling 用户停止键入后0.3秒后的更改应显示在标签中,但订阅onNext不会调用

override func viewDidLoad() {
    ...
    let disposeBag = DisposeBag()
    textfield.rx.text.orEmpty
        .debounce(.milliseconds(300), scheduler: MainScheduler.instance)
        .subscribe(onNext: { [unowned self] (text) in
            self.label.text = text
        }).disposed(by: disposebag)
    ...
}

Using Swift 5 使用Swift 5

pod 'RxSwift', '~> 5'
pod 'RxCocoa', '~> 5'

The solution is to declare disposebag outside of the viewDidLoad() scope: 解决方案是在viewDidLoad()范围之外声明disposebag

let disposebag = DisposeBag()

override func viewDidLoad() {
    super.viewDidLoad()

    ...

    textfield.rx.text.orEmpty
        .debounce(.milliseconds(1000), scheduler: MainScheduler.instance)
        .subscribe(onNext: { [unowned self] (text) in
            self.label.text = text
            print("Yo")
        }).disposed(by: disposebag)
}

Since in your code, the disposebag lives inside the viewDidLoad() scope, once this method ends, the disposebag is deallocated, which cancels the subscription. 因为在您的代码中, disposebag位于viewDidLoad()范围内,所以一旦此方法结束, disposebag释放,从而取消订阅。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM