Home / IOS Development / How to initialize @ObservedObject or @StateObject based on other variables? : iOSProgramming

How to initialize @ObservedObject or @StateObject based on other variables? : iOSProgramming



I am trying to initialize an @ObservableObject with some parameters based on other variables that are initialized when View is created

For example:

struct SignUpView: View {
    var handleSignUpComplete: (Bool, Error) -> Void
    @ObservedObject var viewModel = SignUpViewModel()
    
    var body: some View {
        // ...
    }
}

class SignUpViewModel {
    var handleSignUpComplete: (Bool, Error) -> Void

    init(handleSignUpComplete: (Bool, Error) -> Void) {
        self.handleSignUpComplete = handleSignUpComplete
    }
}

I know I will not be able to do such a thing @ObservedObject var viewModel = SignUpViewModel(handleSignUpComplete: handleSignUpComplete)

Is there a way to create this ObservableObject in init constructor for SignUpView? The only “solution” I have come across is to set the SignUpViewModel parameters in a different way: use default initial values ​​during construction of SignUpViewModel and so on View.onAppear, enter correct values; this seems like a workaround and not a proper solution.

Thanks!


Source link