[转] Combine学习笔记 - @Published properties

参考链接: https://github.com/AvdLee/CombineSwiftPlayground

4天前 5次点击 来自 移动端

标签: 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" ""

Made with in Shangrao,China By Devler.

Copyright © Devler 2012 - 2022

赣ICP备19009883号-1