Salman500
Salman500

Reputation: 1211

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'

Upvotes: 2

Views: 1335

Answers (1)

ielyamani
ielyamani

Reputation: 18591

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.

Upvotes: 11

Related Questions