How to use nested ObservableObject in SwiftUI
Issue #694
I usually structure my app to have 1 main ObservableObject
called Store
with multiple properties in it.
1 | final class Store: ObservableObject { |
SwiftUI for now does not work with nested ObservableObject
, so if I pass Store
to PricingView, changes in PricingPlan
does not trigger view update in PricingView.
1 | struct MainView: View { |
There are some workarounds
Pass nested ObservableObject
So that View observes both parent and nested objects.
1 | PricingView( |
Use struct
This forces us to deal with immutability also, as with reference type PricingPlan, someone could just save a reference to it and alter it at some point.
1 | struct PricingPlan {} |
Listen to nested objects changes
Every ObservableObject
has a synthesized property objectWillChange
that triggers when any @Publisshed
property changes
1 | final class Store: ObservableObject { |