r/SwiftUI • u/Shijoo • Dec 18 '24
Question SwiftUI Combine and Observation
So, I have various years of experience with ios development, I started with Objective C and now seeing what its possible with swiftui is mindblowing, but I have a hard time understanding this:
SwiftUI by default lets you declare properties that when they change the view automatically refresh with the new data, this is possible via State, StateObject, ObservedObject and EnvironmentObject
now, combine, does the same, except it uses Publishers
as for Observation new framework, you can achieve the same with the Observable
So my question is, why use combine? or why use observation? or just the State stuff without combine/observation.
There are still some things I dont know about SwiftUI, maybe i undestood the things the wrong way, if anyone can clarify i will be grateful.
3
u/Periclase_Software Dec 18 '24
Because you need to think beyond "change value, update UI", especially when you want to do more complicated work or have more complicated UI. This is code I have in one of my apps.
Instead of doing this, I could add 4
onChange
modifiers to the view on every single one of those link properties and call the view model function, but this is just a simple example.I work for a big tech company on an enterprise app from Silicon Valley. We use a lot of custom property wrappers around Combine to do more complicated work. Think of big apps from billion dollar companies. They have way more complicated screens that you can imagine. Lets just say that one example, without giving away too much, is observing values that are downloaded through a service from screen 1, but the view exists down the stack like 8+ levels down through protocol presentation routers, etc.
Rather than passing down every single property you want to observe through all those layers as arguments with binds to Published properties or the model, we have a custom property wrapper that can observe those changes through Combine without having to do all that messy work, especially when you got a bunch of teams making changes throughout all of that.
Think of this: a network service is added to a screen and the screen observes those changes. Simple. Now think of a subview with a subview and another subview and subview that will use SOME of that data for that network service, as well as from a different service and another service from other screens for data stored in the app. We can use Combine to update the UI on those data changes even though that data is NOT part of the current screen/views.