2020-12-22 10:09:18 +00:00
|
|
|
// SPDX-License-Identifier: MIT
|
2023-02-14 15:10:32 +00:00
|
|
|
// Copyright © 2018-2023 WireGuard LLC. All Rights Reserved.
|
2020-12-22 10:09:18 +00:00
|
|
|
|
|
|
|
import Foundation
|
|
|
|
|
|
|
|
/// This source file contains bits of code from:
|
|
|
|
/// https://oleb.net/blog/2018/01/notificationcenter-removeobserver/
|
|
|
|
|
|
|
|
/// Wraps the observer token received from
|
|
|
|
/// `NotificationCenter.addObserver(forName:object:queue:using:)`
|
|
|
|
/// and unregisters it in deinit.
|
|
|
|
final class NotificationToken {
|
|
|
|
let notificationCenter: NotificationCenter
|
|
|
|
let token: Any
|
|
|
|
|
|
|
|
init(notificationCenter: NotificationCenter = .default, token: Any) {
|
|
|
|
self.notificationCenter = notificationCenter
|
|
|
|
self.token = token
|
|
|
|
}
|
|
|
|
|
|
|
|
deinit {
|
|
|
|
notificationCenter.removeObserver(token)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
extension NotificationCenter {
|
|
|
|
/// Convenience wrapper for addObserver(forName:object:queue:using:)
|
|
|
|
/// that returns our custom `NotificationToken`.
|
|
|
|
func observe(name: NSNotification.Name?, object obj: Any?, queue: OperationQueue?, using block: @escaping (Notification) -> Void) -> NotificationToken {
|
|
|
|
let token = addObserver(forName: name, object: obj, queue: queue, using: block)
|
|
|
|
return NotificationToken(notificationCenter: self, token: token)
|
|
|
|
}
|
|
|
|
}
|