throttle
throttle 的签名
throttle 的签名func throttle(for: Scheduler.TimeInterval, scheduler: Scheduler) -> Publishers.Throttle<Self>工作原理
示例:基本用法
import Combine
let publisher = PassthroughSubject<Int, Never>()
let subscription = publisher
.throttle(for: .seconds(1), scheduler: DispatchQueue.main, latest: true) // 每秒发出一个事件
.sink { value in
print("Received value: \(value)")
}
// 模拟快速发送值
publisher.send(1)
publisher.send(2)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
publisher.send(3) // 在 1 秒内,这个值会被忽略
}
DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
publisher.send(4) // 1 秒后会发出这个值
}
DispatchQueue.main.asyncAfter(deadline: .now() + 2.5) {
publisher.send(5) // 1 秒后会发出这个值
}输出结果(每秒发出一个值):
throttle 与调度器
throttle 与调度器使用 throttle 处理用户输入
throttle 处理用户输入输出结果(每 2 秒发出一次):
throttle 的注意事项
throttle 的注意事项总结
Last updated