简体   繁体   中英

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

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

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

The solution is to declare disposebag outside of the viewDidLoad() scope:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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