使用 assign(to:) 时 didSet 不会在 @Published 属性上触发

时间:2021-06-14 13:23:05

标签: swift swiftui combine

当由于赋值而改变值时,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 观察者?

0 个答案:

没有答案