xarly
xarly

Reputation: 2154

Enum in viewmodel is not triggering refresh in SwiftUI

I've got a ViewModel which conforms the ObservableObject protocol.

This ViewModel holds a enum variable.

class DeviceViewModel:ObservableObject {
    
    enum ConnectionState: Equatable, CaseIterable {
        case NoConnected
        case Connected
    }
    
    @Published var connectionState: ConnectionState = .NoConnected
    
}

I also got a simple view that it will change the text depending of that enum:

struct ContentView: View {
    let viewModel: DeviceViewModel

    var body: some View {
        if viewModel.connectionState != .NoConnected {
            Text("connected")
        } else {
            Text("No connected")
        }
    }
}

I've noticed that if the enum connectionState changes it won't trigger the view to refresh.

To test this I've added a init method in the ViewModel with the following asyncAfter:

    init() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 5) { [weak self] in
            guard let self = self else {
                return
            }

            self.connectionState = .Connected
            print("self.connectionState: \(self.connectionState)")
        }
    }

Any idea what I'm missing?

Thanks

Upvotes: 1

Views: 494

Answers (2)

JUsltop
JUsltop

Reputation: 84

Use @StateObject to declare your viewModel.

struct ContentView: View {
    @StateObject var viewModel = DeviceViewModel()

    var body: some View {
        if viewModel.connectionState != .NoConnected {
            Text("connected")
        } else {
            Text("No connected")
        }
    }
}

Upvotes: 0

Davyd Geyl
Davyd Geyl

Reputation: 4623

The view needs to observe the changes in order to refresh:

struct ContentView: View {
    @ObservedObject let viewModel: DeviceViewModel
...

Upvotes: 1

Related Questions