I have a multi-staged question.
Scenario: I have a list of user posts, where the list contains only a small subset of information about the post given the size requirement to show a list. Each post in the list can have its individual information expanded by being tapped, which sends the user to a new page, detailing just this post with full detail.
It seems that in this situation, given there is a new screen with new UI and business logic, a @stateobject
should be used for the viewmodel
for this detailed-post-page because it is this new view responsible for the visualization and movement of this specific set of data. First question is just to check this understanding… this is best suited for a @stateobject
, not an @observedobject
right? (I don’t want to use @environmentObject
because only this view will access this data, it shouldn’t be available for the whole app).
Assuming my @stateobject
-for-detailed-page-viewmodel is accurate, I then run into the next problem. Since the stateobject
viewmodel
will facilitate pulling data from the server specific to the parent-view-selected-post, it must receive the postID
from the previous page before its initialization. According to the answer in this post – which references apple docs-, initializing the postID
via a custom init in the view to facilitate this pass to the viewmodel
is good practice as follows:
struct DetailedPostPage: View {
@StateObject private var detailedPostViewModel: DetailedPostViewModel
init(postID: String) {
self.detailedPostViewModel = .init(wrappedValue: .init(postID: passedPostID))
_detailedPostViewModel = StateObject(wrappedValue: DetailedPostViewModel(postID: postID))
}
}
(Side note… which of the two lines in the init is better?)
However, a different answer I have seen to a separate question here comments that I should avoid custom inits in the view to avoid adversely affecting diffing.
This has me confused. There seems to be no way around setting a custom init in the view for a stateobject
viewmodel which requires a passed string. Do I need to avoid these custom inits or not? If I don’t need to and this is in fact best practice for this scenario, how do I know what scenarios not to use it in?