A better notification center to fit swift type checking

Hi,

Currently Foundation framework provides a "design patterns" for broadcasting information using NotificationCenter. This functionality was ported from obj-c and misses generics feature that swift provides. Which makes it hard to use and maintain over time.

In order to use payload of posted notification, it requires type casting and checking. Not mentioning that most of the time debug mode + breakpoints are used to identify correct type of payload.

Can we have a new implementation where public notifications are exposed as enum instead of scattered Strings. Also exposing it's payload type.

I propose something like:

// declare your notifications
extension Notifications {
    static let sessionClosed = Notification<Error?, String>() // payload, identity of payload

    // Ex: group similar notifications toghether
    enum Keyboard {
        static let willShow = Notification<KeyboardInfo>()
        static let didShow = Notification<KeyboardInfo>()
    }
}

// trigger notification
Notifications.sessionClosed.post(error)


// register observer
Notifications.sessionClosed.addObserver(self) { (self, error) in

}

Here is the interface:

// interface
enum Notifications {
    public class Notification<T, Identifier: Equatable> {
        // hold onto returned value to have your callback trigger
        public func register(identifier: Identifier? = nil, callback: @escaping (T) -> Void) -> Any
        
        public func post(_ payload: T, identifier: Identifier? = nil)
        
        /// only while onwer is alive, callback will be triggered. No need to unregister
        public func addObserver<Observer: AnyObject>(_ observer: Observer, identifier: Identifier? = nil, callback: @escaping (Observer, T) -> Void)
        
        /// remove all observations registered by owner
        public func remove(owner: AnyObject)
    }
}

Here is the full implementation for above interface:

It will be great to have a better tool for this case.

Thanks

It would also be useful to include NSNotificationCenter's feature of sending notifications on a specific dispatch queue.

1 Like

Yes, it's missing dispatch notifications on a specific queue and the option to register a selector.