[RxSwift] debounce 和 throttle

2022-07-11  本文已影响0人  巨馍蘸酱
// 防抖 (TextField一直输入时, 忽略 2 秒内的响应, 停止输入 2 秒后响应一次)
usernameTextField.rx.text
    .debounce(RxTimeInterval.seconds(2), scheduler: MainScheduler.instance)
    .subscribe(onNext: { str in
        let date = Date()
        let format = DateFormatter()
        format.dateFormat = "HH:mm:ss"
        print("debounce: \(format.string(from: date)) - \(str)")
    }).disposed(by: disposeBag)

// 节流 (TextField一直输入时, 每 2 秒触发一次)
usernameTextField.rx.text
    .throttle(RxTimeInterval.seconds(2), scheduler: MainScheduler.instance)
    .subscribe(onNext: { str in
        let date = Date()
        let format = DateFormatter()
        format.dateFormat = "HH:mm:ss"
        print("throttle: \(format.string(from: date)) - \(str)")
    }).disposed(by: disposeBag)

throttle: 16:13:56 - Optional("1") 连续不间断输入
throttle: 16:13:57 - Optional("111")
throttle: 16:13:59 - Optional("1111111")
throttle: 16:14:01 - Optional("111111111")
throttle: 16:14:03 - Optional("1111111111111") 此处停止输入
debounce: 16:14:05 - Optional("1111111111111")

上一篇下一篇

猜你喜欢

热点阅读