I have a graphical user interface made of several SwiftUI components (lets call them subviews). These subviews communicate with each other with the help of ObservableObject / ObservedObject. When changes are made to one view, the other view is automatically notified and updates itself.
However, one of the subviews is not a SwiftUI view but a SpriteKit SKScene. Here, too, I would like to react to the changes in an observed value. But I do not have a view that updates automatically. I want to make adjustments to the sprites, depending on the observed value.
How can I be notified of changes in the value? Can I call a method as soon as the value of the ObservedObject changes?
It is easy to observe changes in ObservedObject from UIKit or SKScene. The example below is from UIViewController, change this for the equivalent to SKScene:
import Combine
class Object: ObservableObject {
@Published var value: Int = 10
@Published var anotherValue: String = "Hello"
}
class MyViewController: UIViewController {
let observedObject = Object()
var cancellableBag = Set<AnyCancellable>()
override func viewDidLoad() {
super.viewDidLoad()
// REACT TO ANY @PUBLISHED VARIABLE
observedObject.objectWillChange.sink {
// Do what you want here
}.store(in: &cancellableBag)
// REACT ONLY TO ONE SPECIFIED @PUBLISHED VARIABLE
observedObject.$value.sink { value in
// Do what you want here
}.store(in: &cancellableBag)
}
}
Note that @Published is a propertyWrapper with projectedValue. The projectedValue in this case is the Publisher, that emits events every time the wrappedValue will be changed, so in order to access to the projectedValue it is necessary to call $value instead of value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With