Home > database >  Enum in viewmodel is not triggering refresh in SwiftUI
Enum in viewmodel is not triggering refresh in SwiftUI

Time:11-08

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

CodePudding user response:

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

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

CodePudding user response:

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")
        }
    }
}
  • Related