SwiftUI Combine Why can't bind data in init?

Viewed 107

I am trying a very simple test to just combine a simple Just("JustValue") to a property. But it did not work.
↓ This is my code

struct ResponseView: View {
    
    private var contentCancellable: AnyCancellable? = nil
    @State var content: String = "InitialValue"
    
    var body: some View {
        Text(content)
    }

    init() {
        contentCancellable = Just("JustValue").assign(to: \.content, on: self)
    }
}

Is there anyone know why the Text shows "InitialValue" instead "JustValue"

1 Answers

This is specific of state property wrapper initialization pass... the external state storage is created later so only one initialisation is applied.

If you want to update it, do it later, when state be already created and linked to view, like

struct ResponseView: View {
    
    @State var content: String = "InitialValue"
    
    var body: some View {
        Text(content)
            .onAppear {
                _ = Just("JustValue").assign(to: \.content, on: self)
            }
    }
}

the gives UI which you expected.

Related