PublishedKVO

build tests language license

platform Twitter

Ethereum Litecoin

PublishedKVO 为使用 Key-Value-Observing (KVO,要求类基于 NSObject) 的类类型提供了 Apple 的 Combine @Published@PublishedKVO 基于一个或多个键路径自动发布对象。注意:当与 SwiftUI 一起使用时,可能会出现意外的结果,因为此发布者通常在对象内部的值设置之后(以及在变量被覆盖/重新赋值的情况下之前)发出值,而不是像基于 structs willSet 的 @Published 那样总是在之前发出 - 这主要与 SwiftUI 的 diffing 和/或动画功能有关,可能。

要求

安装

Swift Package Manager

Swift Package Manager 是一个用于自动化 Swift 代码分发的工具,并已集成到 swift 编译器中。

在 Xcode 项目查看器中添加 Package URL https://github.com/matis-schotte/PublishedKVO.git。将其作为依赖项添加到另一个 Package 中,就像将其添加到你的 Package.swiftdependencies 值中一样简单。

dependencies: [
	.package(url: "https://github.com/matis-schotte/PublishedKVO.git", from: "0.1.0")
]

用法

class Example {
	@PublishedKVO(\.completedUnitCount)
	var progress = Progress(totalUnitCount: 2)
	
	@Published
	var textualRepresentation = "text"
}

let ex = Example()

// Set up the publishers
let c1 = ex.$progress.sink { print("\($0.fractionCompleted) completed") }
let c1 = ex.$textualRepresentation.sink { print("\($0)") }

// Interact with the class as usual
ex.progress.completedUnitCount += 1
// outputs "0.5 completed"

// And compare with Combines @Published (almost°) same behaviour
ex.textualRepresentation = "string"
// outputs "string"

ex.$progress.emit() // Re-emits the current value
ex.$progress.send(ex.progress) // Emits given value

° 请参阅上面关于 SwiftUI 的 Attention 注释以及以下示例

class Example {
	@PublishedKVO(\.completedUnitCount)
	var progress1 = Progress(totalUnitCount: 5)
	
	@Published
	var progress2 = Progress(totalUnitCount: 5)
	
	@Published
	var progress3 = "0.0"
}

let ex = Example()

// Class using @PublishedKVO
let c1 = ex.$progress1.sink { print("$progress1 incomming \($0.fractionCompleted) actual \(ex.progress1.fractionCompleted)") }
// Class using @Published
let c2 = ex.$progress2.sink { print("$progress2 incomming \($0.fractionCompleted) actual \(ex.progress2.fractionCompleted)") }
// Struct using @Published
let c3 = ex.$progress3.sink { print("$progress3 incomming \($0) actual \(ex.progress3)") }

ex.progress1.completedUnitCount += 1
ex.progress2.completedUnitCount += 1
ex.progress3 = "0.2"

ex.progress1.completedUnitCount += 1
ex.progress2.completedUnitCount += 1
ex.progress3 = "0.4"

/* Outputs (incomming should new value, actual should be old value):
$progress1 incomming 0.0 actual 0.0
$progress2 incomming 0.0 actual 0.0
$progress3 incomming 0.0 actual 0.0

$progress1 incomming 0.2 actual 0.2
// no output from $progress2
$progress3 incomming 0.2 actual 0.0

$progress1 incomming 0.4 actual 0.4
// no output from $progress2
$progress3 incomming 0.4 actual 0.2
*/

待办事项

许可证

PublishedKVO 在 Apache-2.0 许可证下可用。有关更多信息,请参阅 LICENSE 文件。

作者

Matis Schotte, dm26f1cab8aa26@ungeord.net

https://github.com/matis-schotte/PublishedKVO