当由于赋值而改变值时,didSet 观察器不会触发。这是错误还是功能?
struct ContentView: View {
@StateObject var v = vm()
var body: some View {
Text(String(v.b))
.padding()
}
}
class vm: ObservableObject {
@Published var b = false {
didSet {
print("hello didSet \(b)")
}
}
let pub = CurrentValueSubject<Bool, Never>(false)
init() {
b = true
pub.assign(to: &$b)
pub.send(true)
pub.send(false)
}
}
预期输出:
<块引用>hello didSet true
hello didSet false
hello didSet true
hello didSet false
实际输出:
<块引用>hello didSet true
使用 .sink()
分配值是一种解决方法,但为什么 assign(to:)
不会触发 didSet
观察者?