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)
}
}