I am new to SwiftUI and attempting to grasp the finest strategy to share authenticated person state (AuthSession) throughout views.
After login, I fetch the token and present person, then name:
authSession.login(person: person, token: token)
authSession is an ObservableObject injected by way of @EnvironmentObject.
I need to use authSession.currentUser in different views, however I run into points when attempting to make use of it in init() to initialize a @StateObject ViewModel.
For instance:
@EnvironmentObject var authSession: AuthSession
@StateObject personal var viewModel = FeedViewModel(person: authSession.currentUser!) // ❌ Error
This forces me to defer initialization utilizing .onAppear, which seems like a workaround:
@State personal var viewModel: FeedViewModel?
.onAppear {
if viewModel == nil {
viewModel = FeedViewModel(person: authSession.currentUser!)
}
}
What I need:
- Share
authSessionthroughout the app - Have the ability to initialize ViewModels that depend upon it (e.g. want
tokenorperson) - Keep away from deferring the whole lot to
.onAppear
Query:
How can I cleanly share authSession and use it to initialize ViewModels with out .onAppear hacks?
Any beneficial patterns or structure for this?

