具有自动依赖跟踪的 Swift 简单状态管理
快速信号
警告 这个库仍在开发中,还不能工作。
Signals 是一个高性能的状态管理库,有两个主要目标:
- 尽可能轻松地为小型到复杂的应用程序编写业务逻辑。无论您的逻辑多么复杂,您的应用程序更新都应该保持快速,无需您考虑。Signals 在后台自动优化状态更新,以触发最少的必要更新。默认情况下,它们是懒惰的,会自动跳过没人听的信号。
- 集成到框架中,就好像它们是本机内置原语一样。您不需要任何选择器、包装函数或其他任何东西。可以直接访问信号,当信号值发生变化时,您的视图将自动重新呈现。
指南/API
信号库公开了两个类和一个函数,它们是对您能想到的任何业务逻辑进行建模的构建块。这些结构建立在 Swift 的@Observable
宏和Observation
运行时之上。
Signal<Wrapped>(_: Wrapped)
import SwiftSignals
let counter = Signal(0)
// Read value from signal, prints: 0
print(counter.value)
// Write to a signal
counter.value = 1
signal.peek()
let counter = Signal(0)
let effectCount = Signal(0)
effect {
print(counter.value)
// Whenever this effect is triggered, increase `effectCount`.
// But we don't want this signal to react to `effectCount`
effectCount.value = effectCount.peek() + 1
}
Computed<Wrapped>(_: () -> Wrapped)
import SwiftSignals
let name = Signal("Jane")
let surname = Signal("Doe")
let fullName = Computed {
name.value + " " + surname.value
}
// Prints: "Jane Doe"
print(fullName.value)
// Updates flow through computed
name.value = "John"
// Prints: "John Doe"
print(fullName.value)
effect(_: () -> Void)
import SwiftSignals
let name = Signal("Jane")
let surname = Signal("Doe")
let fullName = Computed {
name.value + " " + surname.value
}
// Prints: "Jane Doe"
effect {
print(fullName.value)
}
// Updating one of its dependencies will automatically trigger
// the effect above, and will print "John Doe" to the terminal.
name.value = "John"