2 // NotificationCenterExtension.swift
5 // Created by Hori,Masaki on 2017/10/29.
6 // Copyright © 2017年 Hori,Masaki. All rights reserved.
11 extension NotificationCenter {
13 func addObserverOnce(forName name: NSNotification.Name?, object obj: Any?, queue: OperationQueue?, using block: @escaping (Notification) -> Void) {
15 weak var token: NSObjectProtocol?
16 token = addObserver(forName: name, object: obj, queue: queue) { [weak self] notification in
18 self.map { me in token.map(me.removeObserver) }
24 extension NotificationCenter {
26 /// Notificationを待って値が設定される Future<T>を返す
29 /// - name: Notification.Name
32 /// Parameters: Notification
33 /// Returns: `T?` : 成功時は `T`, エラー時は例外を発生させる。 監視を継続するときは `nil`を返す
34 /// - Returns: Notificationによって値が設定される Future<T>
35 func future<T>(name: Notification.Name, object: Any?, block: @escaping (Notification) throws -> T?) -> Future<T> {
37 let promise = Promise<T>()
39 weak var token: NSObjectProtocol?
41 .addObserver(forName: name, object: object, queue: nil) { notification in
45 guard let value = try block(notification) else {
50 promise.success(value)
54 promise.failure(error)
57 token.map(self.removeObserver)