快速合并发布两次

时间:2020-09-01 22:50:01

标签: swift swiftui combine

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?
  • 有什么更好的方法来删除重复项?

1 个答案:

答案 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 "" ""