I need to plant a notification for using the notification center, which I started planting my observer in my class initialization, which I am not sure it is a correct place, but some time if we made a mistake in coding and we created more than one observer how we can solve the issue?
For creating this issue I made a button for that to making multiple observers, so now if I press on the button a new observer is going created and making same work more than once.
import SwiftUI
struct ContentView: View {
@StateObject var myScreen: MyScreen = MyScreen.shared
var body: some View {
Button("plantNotificationObserver") {
myScreen.plantNotificationObserver()
}
if let size: CGSize = myScreen.visibleFrame?.size {
Text("visibleFrame size: " + String(describing: size))
.animation(.default, value: size)
}
}
}
class MyScreen: ObservableObject {
static let shared: MyScreen = MyScreen()
init() {
plantNotificationObserver()
}
@Published var visibleFrame: NSRect? = NSScreen.main?.visibleFrame
func plantNotificationObserver() {
NotificationCenter.default.addObserver(forName: NSApplication.didChangeScreenParametersNotification, object: NSApplication.shared, queue: .main) { notification in
print("screen parameters changed")
self.visibleFrame = NSScreen.main?.visibleFrame
}
}
}
Is there a way to list all my alive observers and killing the duplicated ones? I want have a bird view over my observers and correcting them in case if I made a mistake and created more than what I wanted?