import UIKit
import Combine
//以下是ObservableObject协议
/*
public protocol ObservableObject : AnyObject {
/// The type of publisher that emits before the object has changed.
associatedtype ObjectWillChangePublisher : Publisher = ObservableObjectPublisher where Self.ObjectWillChangePublisher.Failure == Never
/// A publisher that emits before the object has changed.
var objectWillChange: Self.ObjectWillChangePublisher { get }
}
*/
class ViewModel: ObservableObject{
@Published var publishedString: String = "old published value"
@Published var publishedNumber: Int = 0
var number = 0
var str = "test"
}
let vm: ViewModel = .init()
//objectWillChanged的默认类型是ObjectWillChangePublisher,而ObjectWillChangePublisher的Output是Void
//另外需要注意,改变value的值也会触发objectWillChange
vm.objectWillChange.sink { (output) in
print("object will change \(output)")
}
//1
vm.publishedString = "new published value"
//官方文档对于Published的描述是:A type that publishes a property marked with an attribute.
//从测试来看,新的订阅是会收到最新的值的
vm.$publishedString.sink { (value) in
print("test published: \(value)")
}
//2
vm.publishedString = "hi published value"
//3
//改变多个Published属性时,都会触发objectWillChanged
vm.publishedNumber = 1
//改变非Published属性不会触发objectWillChange
print("----------------------")
vm.number = 1
vm.str = "tttt"
打印:
object will change ()
test published: new published value
object will change ()
test published: hi published value
object will change ()
----------------------