Search code examples
statecombinesink

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)

            }
        }
    }
}

Solution

  • 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