How to swap my @State of my SwiftUI view for my view model @Published variable?

Viewed 1413

I have a button that triggers my view state. As I have now added a network call, I would like my view model to replace the @State with its @Publihed variable to perform the same changes.

How to use my @Published in the place of my @State variable?

So this is my SwiftUI view:

struct ContentView: View {

  @ObservedObject var viewModel = OnboardingViewModel()

  // This is the value I want to use as @Publisher
  @State var isLoggedIn = false

  var body: some View {
    ZStack {
      Button(action: {
        // Before my @State was here
        // self.isLoggedIn = true
        self.viewModel.login()
      }) {
        Text("Log in")
      }

      if isLoggedIn {
        TutorialView()
      }
    }
  }
}

And this is my model:

final class OnboardingViewModel: ObservableObject {

  @Published var isLoggedIn = false

  private var subscriptions = Set<AnyCancellable>()

  func demoLogin() {
    AuthRequest.shared.login()
      .sink(
        receiveCompletion: { print($0) },
        receiveValue: {
          // My credentials
          print("Login: \($0.login)\nToken: \($0.token)")
          DispatchQueue.main.async {
            // Once I am logged in, I want this
            // value to change my view.
            self.isLoggedIn = true } })
      .store(in: &subscriptions)
  }
}
2 Answers

Remove state and use view model member directly, as below

struct ContentView: View {

  @ObservedObject var viewModel = OnboardingViewModel()

  var body: some View {
    ZStack {
      Button(action: {
        self.viewModel.demoLogin()
      }) {
        Text("Log in")
      }

      if viewModel.isLoggedIn {    // << here !!
        TutorialView()
      }
    }
  }
}

Hey Roland I think that what you are looking for is this:

$viewMode.isLoggedIn

Adding the $ before the var will ensure that SwiftUI is aware of its value changes.

struct ContentView: View {

  @ObservedObject var viewModel = OnboardingViewModel()

  var body: some View {
    ZStack {
      Button(action: {
        viewModel.login()
      }) {
        Text("Log in")
      }

      if $viewMode.isLoggedIn {
        TutorialView()
      }
    }
  }
}



class OnboardingViewModel: ObservableObject {

    @Published var isLoggedIn = false

    
    func login() {
       isLoggedIn = true
    }
}
Related