Currently I am using addObserver method to receive my wished notification in my ObservableObject, from the other hand we can use publisher method to receive wished notification in a View, I like to use publisher method inside my ObservableObject instead of addObserver method, how could I do that? How can I receive/notified the published value from publisher in my class?
import SwiftUI
struct ContentView: View {
@StateObject var model: Model = Model()
var body: some View {
Text("Hello, world!")
.padding()
.onReceive(orientationDidChangedPublisher) { _ in
print("orientationDidChanged! from View")
}
}
}
var orientationDidChangedPublisher = NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification)
class Model: ObservableObject {
init() { orientationDidChangeNotification() }
private func orientationDidChangeNotification() { NotificationCenter.default.addObserver(self, selector: #selector(readScreenInfo), name: UIDevice.orientationDidChangeNotification, object: nil) }
@objc func readScreenInfo() { print("orientationDidChanged! from ObservableObject") }
}