I am having an issue with understanding what it means when it talks about state objects. What is a state object? How do you use it? What are the differences between the different objects mentioned in the course, e.g. @StateObject, @EnvironmentObject etc.?
Any help would be appreciated.
Couple of things to unpack here since this is not a simple question that can be answered quickly, since it pertains to a design concept (state management). State management is not as simple as it could sound (for example, one thing is state management in a simple app, another is state management in an operating system, or even in the context of the computer itself [CPU, RAM, Disk, etc]). In general, state management is keeping control of the state of things, kind of like a playbook for what to do in situations that happen (e.g.: if the mouse button is pressed, this sends a signal through hardware that gets picked up by the OS, then it processes it etc etc).
Within state management, there are language patterns and strategies that help to abstract and therefore ease the use of it. So Swift UI for example uses @StateObject, @EnvironmentObject, and things like that, but other frameworks will have different tools available to them. I’ll leave this link for you to start piecing out the differences: https://www.hackingwithswift.com/quick-start/swiftui/whats-the-difference-between-observedobject-state-and-environmentobject
I recommend trying simple examples: like, make an app with few views and try to apply these.
An analogy of state management in the context of a website: i have two links: myPhotos and myFriends to some website I log into. They allow me to change and adjust my photos and friend contacts respectively. For the sake of simplicity, myFriends can’t see photos from myPhotos, and myPhotos can’t see friend info from myFriends. However, what they share in common is that they know that my username is logged on in common to both of them (so for example, if i click on myPhotos after myFriends, it won’t show a different users photos).
So here we have
- data whose state is local to the particular pages: (the photos and the friend info).
- data that’s global to both the pages (my username)
So global here would be like @EnvironmentObject, and the local would be like @State.
It’s a very loose toy example but should give an idea.
You may also want to read about the pub-sub pattern: Publish–subscribe pattern - Wikipedia
1 Like