About SwiftUI @Published

Asked 1 years ago, Updated 1 years ago, 99 views

I'm reading the Apple document, but I don't understand it.
Documents

class Weather {
    @Published variable temperature—Double
    init(temperature:Double) {
        self.temperature=temperature
    }
}

let weather = Weather (temperature:20)
cancelable=weather.$temperature
    .sink(){
        print("Temperature now:\($0)")
}
weather.temperature=25

If you do this,
// Temperature now: 20.0
// Temperature now:25.0
It says, but why is 20.0?
After generating the Weather class, that is, the temperature has already entered and the publisher is registered afterwards, so
I don't think the publisher will work for 20, but it will actually output 20.

Please let me know if you understand.

swift swiftui combine

2022-09-30 11:35

1 Answers

I guess weather.temperature is the CurrentValueSubject.
Subject|Apple Developer Documentation

The expected behavior seems to be from another subject, PassthroughSubject.
e.g.

let relay=PassthroughSubject<String, Never>()

relay.send("Hello") // no output
let subscription=relay
    .sink {value in
        print("subscription1 received value:\(value)")
}

relay.send("World!")//=>World!

Comparison Code

let variable=CurrentValueSubject<String, Never>("")

variable.send("Initial text")

let subscription2 = variable.sink {value in
    print("subscription2 received value:\(value)")
}

variable.send("More text")
// subscription2 received value —Initial text
// subscription2 received value:More text


2022-09-30 11:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.