[SwiftUI] Data passing + Observation

I am learning more SwiftUI and building some dummy apps. I am trying to transform an @Published property into another @Published property which will be the one that the View uses. The LocationManager is a class that publishes a location retrieved from CoreLocation. The location gets converted into a MKCoordinateRegion which is consumed by MapCameraPosition which is ultimately what the view cares about.

Is this approach a standard pattern in SwiftUI - where we map and assign.

So your question is: you have two @ObservableObject A and B and would like to propagate the change in A to B. Yes, I think your approach of using Combine API is correct.

BTW, @Observable in your diagram seems to be a typo for @ObservableObject. @Observable is a macro introduced in Swift 5.9 and will replace @ObservableObject in SwiftUI 5.

1 Like

Thank you for the response. In searches for SwiftUI examples on Google and Github, the examples I found simply bound primitive data types from the ViewModel. I haven't found good realistic examples. My search terms may just be incorrect.

I did intend @Observable from Observation as I am using Swift 5.9 features. From the WWDC they seem to treat the new @Observable macro practically the same as conformance to ObservableObject. However, I don't mind using the older method.

After exploring some more, I realise that if the LocationManager has a completion closure that returns the location, it will simplify the bindings. That way, the LocationManager does not need to be Observable. If it was updating constantly with the user's live location, making the location Observable may be better.

Do you mean how to pass data between two models of reference type? I couldn't find examples for SwiftUI 5 either, but there should be many for SwiftUI 4.

Note: ObservableObject is a Combine API, not SwiftUI API. Your question is actually a typical Combine use case. I think you have better chance to find examples in Combine tutorials.

Ah, then I think you misunderstood it. The new Observable APi is Combine free, so you shouldn't use @Published or Combine API. I'm also curious what's the recommended way to pass data between two objects in the new API. I guess it might be withMutation()[ [Second review] SE-0395: Observability - #48 by Philippe_Hausler], but in my opinion it's not as easy to use as the Combine API (I'd be glad to proved wrong). Another possibility is withObservationTracking()[ withObservationTracking(_:onChange:) | Apple Developer Documentation], but I doubt it.

I think it will be easier to start with the old API. But if you are not in hurry, it would be worth learning the new API. That said, it's important to have a good understanding of the solution to this question.

If I understand it correctly, you meant you can avoid the original question by using just one Observable, right? But I still think it's important to figure out the original question.