DEV Community

hori,masaki
hori,masaki

Posted on

Observing notification only once

extension NotificationCenter {

    func addObserverOnce(forName name: NSNotification.Name?, object obj: Any?, queue: OperationQueue?, using block: @escaping (Notification) -> Void) {

        weak var token: NSObjectProtocol?
        token = addObserver(forName: name, object: obj, queue: queue) {notification in

            token.map(self.removeObserver)
            block(notification)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)