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.$isSubmitAllowed.sink { _ in
print("Form changed: \(form.isSubmitAllowed) \"\(form.username)\" \"\(form.password)\"")
}
form.isSubmitAllowed = false
form.isSubmitAllowed = false
form.isSubmitAllowed = false
输出为:
Form changed: true "" ""
Form changed: true "" ""
Form changed: false "" ""
Form changed: false "" ""
我的问题是:
true
输出2,而false
仅2?答案 0 :(得分:1)
为什么真输出为2而假输出只有2?
创建formSubscription
时将运行第一个输出。接下来的三个是由您连续的form.isSubmitAllowed = false
语句触发的。
请注意,您将form.isSubmitAllowed
更改为false
三次,并且在输出中仅发生两次:
form.isSubmitAllowed = false
form.isSubmitAllowed = false
form.isSubmitAllowed = false
// Form changed: true "" ""
Form changed: true "" ""
Form changed: false "" ""
Form changed: false "" ""
这是因为您不是打印更改的值,而是打印旧的值。
尝试以下方法:
let formSubscription = form.$isSubmitAllowed.sink { isSubmitAllowed in
print("Form changed: \(isSubmitAllowed) \"\(form.username)\" \"\(form.password)\"")
}
此打印:
// Form changed: true "" ""
Form changed: false "" ""
Form changed: false "" ""
Form changed: false "" ""
如果要删除重复项,只需使用removeDuplicates
:
let formSubscription = form.$isSubmitAllowed.removeDuplicates().sink { value in
print("Form changed: \(value) \"\(form.username)\" \"\(form.password)\"")
}
form.isSubmitAllowed = false
form.isSubmitAllowed = false
form.isSubmitAllowed = false
此打印:
Form changed: true "" ""
Form changed: false "" ""