Sharing state objects with multiple Views using @EnvironmentObject
In many cases, there are dependent collaborators that must be shared between several Views, even without having a tight relationship between them. Think of a ThemeManager
, or a NetworkManager
, or a UserProfileManager
.
Passing them through the chain of Views can be annoying, without even thinking of the coupling we could create. If a view doesn't need the NetworkManager
instance, for example, it should still have it as a property in case one of its child
Views needs it.
SwiftUI solves this with the concept of Environment
, a place to add common objects – usually ObservableObject
objects – that will be shared between a chain of Views. An Environment
is started in the root ancestor of the view graph and can be changed further down in the chain by us adding new objects.
To present this feature, we are going to implement a basic song player with three Views:
- A View for the list of songs...