Chr1s78
Chr1s78

Reputation: 33

swiftui cannot change @State value in sink

i am learning swiftui now and I am newbie for stackoverflow, I find a question,this is my code. I want to change the @State nopubName in sink ,but it's not work,the print is always "Nimar", I don't know why

struct ContentView: View {
   
    @State var nopubName: String = "Nimar"
    private var cancellable: AnyCancellable?
    
    var stringSubject = PassthroughSubject<String, Never>()

    init() {
        cancellable = stringSubject.sink(receiveValue: handleValue(_:))
    }
    
    func handleValue(_ value: String) {
         print("handleValue: '\(value)'")
        self.nopubName = value
        print("in sink "+nopubName)
     }
    
    var body: some View {
        VStack {
            Text(self.nopubName)
                .font(.title).bold()
                .foregroundColor(.red)
            Spacer()
 
            Button("sink"){
                stringSubject.send("World")
                print(nopubName)

            }
        }
    }
}

Upvotes: 0

Views: 1039

Answers (2)

Abizern
Abizern

Reputation: 150565

You don't need to use Combine, If you are within the View, you can change the value of @State variables directly

struct ContentView: View {
    @State var nopubName: String = "Nimar"
    var body: some View {
        VStack {
            Text(self.nopubName)
                .font(.title).bold()
                .foregroundColor(.red)
            Spacer()

            Button("sink"){
                nopubName = "World"
            }
        }
    }
}

Upvotes: 0

lorem ipsum
lorem ipsum

Reputation: 29242

You should only access a state property from inside the view’s body, or from methods called by it.

https://developer.apple.com/documentation/swiftui/state

You can get that functionality working in an ObservableObject and update an @Published To keep the UI updated

https://developer.apple.com/documentation/swiftui/managing-model-data-in-your-app

Upvotes: 1

Related Questions