I’ve a multi-staged query.
Situation: I’ve an inventory of consumer posts, the place the checklist comprises solely a small subset of details about every publish given the scale requirement to indicate an inventory. Every publish within the checklist can have its particular person info expanded by being tapped, which sends the consumer to a brand new web page, detailing simply this publish with full element.
Plainly on this state of affairs, given there’s a new display with new UI and enterprise logic, a @stateobject
needs to be used for the viewmodel
for this detailed-post-page as a result of it’s this new view accountable for the visualization and motion of this particular set of knowledge. First query is simply to examine this understanding… that is finest fitted to a @stateobject
, not an @observedobject
proper? (I do not need to use @environmentObject
as a result of solely this view will entry this knowledge, it should not be accessible for the entire app).
Assuming my @stateobject
-for-detailed-page-viewmodel is correct, I then run into the following drawback. Because the stateobject
viewmodel
will facilitate pulling knowledge from the server particular to the parent-view-selected-post, it should obtain the postID
from the earlier web page earlier than its initialization. In accordance with the reply on this publish – which references apple docs-, initializing the postID
by way of a customized init within the view to facilitate this cross to the viewmodel
is sweet observe as follows:
struct DetailedPostPage: View {
@StateObject non-public var detailedPostViewModel: DetailedPostViewModel
init(postID: String) {
self.detailedPostViewModel = .init(wrappedValue: .init(postID: passedPostID))
_detailedPostViewModel = StateObject(wrappedValue: DetailedPostViewModel(postID: postID))
}
}
(Facet notice… which of the 2 strains within the init is best?)
Nonetheless, a distinct reply I’ve seen to a separate query right here feedback that I ought to keep away from customized inits within the view to keep away from adversely affecting diffing.
This has me confused. There appears to be no manner round setting a customized init within the view for a stateobject
viewmodel which requires a handed string. Do I must keep away from these customized inits or not? If I needn’t and that is in reality finest observe for this situation, how do I do know what situations to not use it in?