[转] Combine学习笔记 - @Published properties
参考链接: https://github.com/AvdLee/CombineSwiftPlayground6个月前 • 217次点击 • 来自 移动端
标签: Swift
@Published properties
A Property Wrapper that adds a Publisher
to any property.
ObservableObject
- a class inheriting from
ObservableObject
automagically synthesizes an observable - ... which fires whenever any of the
@Published
properties of the class change
print("\n* Demonstrating ObservableObject")
class ObservableFormViewModel: ObservableObject {
@Published var isSubmitAllowed: Bool = true
@Published var username: String = ""
@Published var password: String = ""
var somethingElse: Int = 10
}
var form = ObservableFormViewModel()
let formSubscription = form.objectWillChange.sink { _ in
print("Form changed: \(form.isSubmitAllowed) \"\(form.username)\" \"\(form.password)\"")
}
form.isSubmitAllowed = false
form.username = "Florent"
form.password = "12345"
form.somethingElse = 0 // note that this doesn't output anything
objectWillChange
监听的是值变化前,且只有@Published
会触发
* Demonstrating ObservableObject
Form changed: true "" ""
Form changed: false "" ""
Form changed: false "Florent" ""