Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save shakemno/a800fb8b3555d0039814018bce4eb321 to your computer and use it in GitHub Desktop.

Select an option

Save shakemno/a800fb8b3555d0039814018bce4eb321 to your computer and use it in GitHub Desktop.
Extension for "NotificationCenter" to observe a notification just once and directly unsubscribe.
//
// NotificationCenter+ObserveOnce.swift
//
// Created by Felix Mau on 18.10.20.
// Copyright © 2020 Felix Mau. All rights reserved.
//
import UIKit
extension NotificationCenter {
/// Adds an observer to the given notification center, which fires just once.
///
/// Note:
/// - Same parameters as "addObserver", but with default properties
/// See http://apple.co/2zZIYJB for details.
///
/// Parameters:
/// - name: The name of the notification for which to register the observer
/// - object: The object whose notifications the observer wants to receive
/// - queue: The operation queue to which block should be added.
/// - block: The block to be executed when the notification is received.
func observeOnce(forName name: NSNotification.Name?,
object obj: Any? = nil,
queue: OperationQueue? = nil,
using block: @escaping (Notification) -> Swift.Void) {
var observer: NSObjectProtocol?
observer = addObserver(forName: name,
object: obj,
queue: queue) { [weak self] notification in
// Here we directly remove the observer, so this closure will be executed just once.
self?.removeObserver(observer!)
block(notification)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment