Skip to content

@StateObject for ViewModels instead of @ObservedObject #8

@JonnyBeeGod

Description

@JonnyBeeGod

I think to be safe we should use @StateObject property wrapper instead of @ObservedObject for the ViewModels.

What I observed in my app when adopting this pattern is, that in some cases SwiftUI completely reinstantiates the whole View hierarchy. This happened in my app e.g. after dismissing a modally presented view again. With @ObservedObjectall viewModel states would be reset to .idle again. For some reason onAppear however is not called again which leaves us forever in the idle state. Using @StateObject will preserve the ViewModel state throughout these reinstantiation cycles

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions