-1

Can ObservableObject be used in Swift? I only see tutorials for it in SwiftUI. I'd like to be able to load an object into memory from an API call. Then use VCs to manipulate different parts of it, and all subsequent VCs respond to it.

vazy
  • 73
  • 1
  • 4
  • 1
    ObservableObject is part of Combine, Combine is a swift-based framework, so it can be used with any swift-based code. – Asperi May 03 '20 at 06:30

1 Answers1

0

Yes, you can use ObservableObject even if you are not using SwiftUI. Keep in mind that use of this requires an iOS 13 minimum.

But if you are not going to use ObservableObject in the context of SwiftUI, ensure you understand how it works. ObservableObject sends updates before the property which holds the updated value is set. This is because the object publishes using the objectWillChange publisher. I am pointing this out because if you use sink on the published value as a mechanism of notifying your VCs that a new value is available and they go to grab the value by referencing a published property directly, they will still get the old value and you won't see your screens update with new data.

When using ObservableObject in SwiftUI you generally don't need to worry about the objectWillChange publisher because the SwiftUI views automatically update whenver that publisher fires. Since regular view controllers by default don't know how to update themselves when these publishers fire, understanding how to implement their updates when using an ObservableObject as the data model is important.

jshapy8
  • 1,983
  • 7
  • 30
  • 60