OSDN Git Service

staticプロパティをインスタンスプロパティに変更
[kcd/KCD.git] / KCD / NotificationCenterExtension.swift
1 //
2 //  NotificationCenterExtension.swift
3 //  KCD
4 //
5 //  Created by Hori,Masaki on 2017/10/29.
6 //  Copyright © 2017年 Hori,Masaki. All rights reserved.
7 //
8
9 import Foundation
10
11 extension NotificationCenter {
12     
13     func addObserverOnce(forName name: NSNotification.Name?, object obj: Any?, queue: OperationQueue?, using block: @escaping (Notification) -> Void) {
14         
15         weak var token: NSObjectProtocol?
16         token = addObserver(forName: name, object: obj, queue: queue) { [weak self] notification in
17             
18             self.map { me in token.map(me.removeObserver) }
19             block(notification)
20         }
21     }
22 }
23
24 extension NotificationCenter {
25     
26     /// Notificationを待って値が設定される Future<T>を返す
27     ///
28     /// - Parameters:
29     ///   - name: Notification.Name
30     ///   - object: 監視対象
31     ///   - block:
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> {
36         
37         let promise = Promise<T>()
38         
39         weak var token: NSObjectProtocol?
40         token = self
41             .addObserver(forName: name, object: object, queue: nil) { notification in
42                 
43                 do {
44                     
45                     guard let value = try block(notification) else {
46                         
47                         return
48                     }
49                     
50                     promise.success(value)
51                     
52                 } catch {
53                     
54                     promise.failure(error)
55                 }
56                 
57                 token.map(self.removeObserver)
58         }
59         
60         return promise.future
61     }
62 }