调节

Regulate 是一个轻量级的库,它为可以在一段时间内发出值的事物带来以下基于时间的调节操作(并且不使用响应式编程或 AsyncSequence)。

Regulate 完全由 Swift 并发支持,并将创建的 Tasks 数量限制到最低。

let regulator = Task.debounce(dueTime: .milliseconds(200)) { (value: Int) in
  print(value)
}

// the created `regulator` can be used across `Tasks` and each call to `regulator.push(x)`
// will feed the regulation system

// the execution of the provided closure will be debounced and executed 200ms after the last call to `push(x)`

Regulate 还提供了 SwiftUI 辅助工具,可以开箱即用地调节按钮和绑定。您可以查看 示例应用程序

对于 Button,它就像这样简单

Button {
  print("I've been hit (throttled)!")
} label: {
  Text("Hit me")
}
.throttle(dueTime: .seconds(1))

对于 Binding,需要稍微多做一些工作

@State private var text = ""
@StateObject private var debouncer = Debouncer<String>(dueTime: .seconds(1))
...
TextField(
  text: self
    .$text
    .perform(regulator: debouncer) { text in
      print("regulated text \(text)") // you can perform any side effect here!
    }
) {
  Text("prompt")
}

演示

Demo Application

将 Regulate 添加为依赖项

要在 SwiftPM 项目中使用 Regulate 库,请将以下行添加到 Package.swift 文件中的依赖项中

.package(url: "https://github.com/sideeffect-io/Regulate"),

"Regulate" 作为可执行目标的依赖项包含

.target(name: "<target>", dependencies: ["Regulate"]),

最后,将 import Regulate 添加到您的源代码中。