Converting between observation methods

We can get informed on object changes through conforming to ObservableObject or having the @Observable macro attached to the type’s definition. How do you handle imported code that assumes the other observation technique?

Thank you for your post.

I find your question quite intriguing, as SwiftUI observable variables are undoubtedly a powerful feature we all use. However, I am not the best developer to provide you examples as I don't use many third parties anymore based on my job. I can provide an example of how I handle third-party libraries that conform to ObservableObject, or at least I did. There is no definitive answer from me, but developers must always adapt to the challenges they encounter.

// ObservableObject wrapper for MyObservableType
class ObservableTypeAdapter: ObservableObject {
    @Published private var myObservable: MyObservableType

When dealing with imported code that employs a different observation technique than the one you are utilizing in your SwiftUI project, you can bridge the gap between the two by employing certain adaptation techniques.

If you have an existing type and require it to be used in a context that expects the macro format, you can create a wrapper that conforms to the expected protocol and publishes changes.

If you have a type annotated with and need to use it in a context that requires , you can create a wrapper that listens to changes on the type and forwards them appropriately.

By creating these wrappers, you can effectively bridge between the two observation models, allowing you to integrate imported code that uses either ObservableObject or @Observable without major conflicts.

Looking forward to get more opinions from other developers and how they handle that as well as examples of observation techniques that they have encountered. This is a great thread to see what developers have encountered in the wild.

Albert Pascual
  Worldwide Developer Relations.

Converting between observation methods
 
 
Q