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 ThemeManager
, or NetworkManager
, or UserProfileManager
.
Passing them through the chain of Views can be really annoying, without thinking of the coupling we could create. If a view doesn't need NetworkManager
, 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, which will be shared between a chain of Views. An Environment
is started in the root ancestor of the view graph, and it can be changed further down in the chain, adding new objects.
To present this feature, we are going to implement a basic song player with three Views:
- A list of songs view
- A mini player view, always on top of...