How we can make and put a custom Notification which fires up with changing a custom variable? (in SwiftUI or UIKit)

Viewed 489

Let's say we created a (var) variable which can be a Bool or String or any kind and we can change this variable with a function or button or anything you imagine. I am interested to build a notification or observation way that put's this value under magnifying glass and it is sensitive to value change of this variable.

How we can make it possible in both platform SwiftUI and UIKit?

PS: I know the usage of @State and .onChange, I am trying to observe with custom way.

1 Answers

You can create a custom notification:

extension Notification.Name {
    static let customNotification = Notification.Name("customNotification")
}

And use it like this:

struct ContentView: View {
    @State var test = 0
    
    var body: some View {
        Button("Increment") {
            test += 1
        }
        .onChange(of: test) { value in
            NotificationCenter.default.post(name: .customNotification, object: value)
        }
    }
}

You may listen to this notification wherever you want. Here is an example for a SwiftUI view:

.onReceive(NotificationCenter.default.publisher(for: .customNotification)) { notification in
    if let value = notification.object as? Int {
        print(value)
    }
}
Related