8.2 C
New York
Saturday, March 1, 2025

ios – Greatest strategy to move knowledge from view initializer to viewmodel in swiftUI?


In case you have an issue, the place you’ve gotten a View which has an Observable Object, and also you need to configure it (not initialising it!) from a parameter offered by the View initialiser, you are able to do the next:

Given an Observable, the place you possibly can ship a “command” (aka occasion) “setOldPassword” with a payload (observe: sure, semantically a view is sending a command/occasion to the observable, it is occasion pushed!):

// Mannequin, ViewModel, Interactor, UseCase, StateHolder ... you title it.
ultimate class Mannequin: ObservableObject {
    @Revealed personal(set) var viewState: ViewState = .init()
    
    func setOldPassword(_ password: String) {
        ...
    }
}

then, you purposefully use a activity modifier for configuring the observable:

struct SetupNewPasswordView: View {
    @StateObject personal var mannequin = Mannequin()
    
    let oldPassword: String
    
    init(oldPassword: String) {
        // Deal with the previous password task logic
        self.oldPassword = oldPassword
    }
    
    var physique: some View {
        ContentView()
            .activity {
                mannequin.setOldPassword(oldPassword)
            }
    }
}

The duty modifier ensures, that will probably be referred to as as soon as and solely as soon as for the life time of the view, which is the intention. Observe, that right now the Mannequin has been already created and that it is usually ensured (due t the @StateObject property wrapper), that this occurs solely as soon as through the creation of the underlying artefact holding the reference to the mannequin.

A activity modifier’s closure runs in a Swift Activity, and this activity will likely be mechanically cancelled when the view disappears. So, you could be positive, that mannequin.setOldPassword(oldPassword) will likely be referred to as as soon as through the initialisation of the underlying artefacts that maintain the view state, after which by no means once more.

Observe, that in SwiftUI, the initialiser of the View construction is not an initialiser of the underlying artefact (view) rendering the pixels! It’s principally the perform parameter for the perform physique, which both creates the underlying artefact or mutates it. Calling it a second time, for a similar underlying view (see additionally: view identification), then it has no impact.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles