Skip to content

View Model reinitialization when referencing "self" within a initializer and conforming to @Observable. #175

Answered by mbrandonw
timbueno asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @timbueno, yes this is to be expected unfortunately, and is a big gotcha with @Observation and SwiftUI, and has nothing to do with this library or our "modern SwiftUI" techniques. We even tweeted about it here and discussed in this episode.

In your HomeViewModel initializer you are accessing self.appState (via bind), and so that tells the view (in this case ScootApp) that it should re-render when that property changes. And so when it does change, that causes ScootApp to re-compute its body, and then you are generating a new model.

Probably the safest way to prevent this is to make it a point to never access the observable computed properties in an initializer, and instead only access t…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@timbueno
Comment options

Answer selected by timbueno
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants