I’ve an iOS app with the next views:
struct LoggedInUserView: View{
@ObservedObject var viewModel: LoggedInUserViewModel
@StateObject var sharedPortionViewModel: SharedPortionViewModel(userName: "")
var physique: some View{
//Some specific-to-LoggedInUser UI parts
SharedPortionUserView(sharedPortionViewModel: sharedPortionViewModel)
}
}
struct OtherUserView: View{
@ObservedObject var viewModel: OtherUserViewModel()
@StateObject var sharedPortionViewModel: SharedPortionViewModel(userName: "")
var physique: some View{
//Some specific-to-OtherUser UI parts
SharedPortionUserView(sharedPortionViewModel: sharedPortionViewModel)
}
}
SharedPortionViewModel
runs the identical capabilities to load knowledge in each instances, but it surely grabs the required person’s information, relying on which view is being seen. 100% of the time LoggedInUserView
is seen, the logged-in-user’s userName might be handed. That is saved in Keychain
.
All I’m making an attempt to do is move the related person’s userName to the creation of the StateObject in each instances, however I’m discovering this surprisingly advanced to do. A wide range of approaches I’ve seen contain customized initializers within the view, which I would wish to keep away from. I additionally thought of one thing like:
var passedUserName: String //tried a wide range of totally different property wrappers
@StateObject var sharedPortionViewModel: SharedPortionViewModel(userName: passedUserName)
Such that the mum or dad view can move the userName in query when loading this view, however I believe there are points with passedUserName not being set at initialization to be able to move to sharedPortionViewModel
.
I additionally thought of modifying the above strategy by:
@State personal var sharedProfileViewModel: SharedUserProfilePageViewModel?
After which initializing it through
.onAppear {
if sharedProfileViewModel == nil {
sharedProfileViewModel = SharedUserProfilePageViewModel(userName: userName)
}
}
However this simply feels bizarre.
I may create the viewModel earlier than initializing the navigation from the mum or dad view, after which move this because the already-created-viewmodel, however this feels clunky.
Am I lacking one thing? Why is that this so concerned? Are these actually the one methods to realize this? Did I cowl one of the best strategy above and improperly dismissed it?