About SwiftUI @Published

Asked 5 months ago, Updated 5 months ago, 21 views

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

class Weather {
    @Published variable temperature—Double
    init(temperature:Double) {

let weather = Weather (temperature:20)
        print("Temperature now:\($0)")

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.

let relay=PassthroughSubject<String, Never>()

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


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

© 2023 OneMinuteCode. All rights reserved.