美文网首页
[RxSwift] debounce 和 throttle

[RxSwift] debounce 和 throttle

作者: 巨馍蘸酱 | 来源:发表于2022-07-11 16:16 被阅读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 节流 (TextField一直输入时, 每 2 秒触发一次)
    • debounce 防抖 (TextField一直输入时, 忽略 2 秒内的响应, 停止输入 2 秒后响应一次)

    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")

    相关文章

      网友评论

          本文标题:[RxSwift] debounce 和 throttle

          本文链接:https://www.haomeiwen.com/subject/ehjabrtx.html