NotificationCenter簡單封裝

背景

當(dāng)使用NotificationCenter發(fā)通知傳遞數(shù)據(jù)時巨朦,通常需要繁復(fù)的解包,麻煩還容易出錯关拒,所以針對該問題對NotificationCenter進(jìn)行了傳遞數(shù)據(jù)模型的封裝思灌。

依賴

由于RxSwift封裝的NotificationCenter對生命周期控制的很好,所以我們基于它開發(fā)发魄。

兼容

考慮到只是對NotificationCenter的封裝,所以我們需要很好的支持NotificationCenter原生功能俩垃。所以開發(fā)都是基于NotificationCenter的擴(kuò)展励幼。

使用

  1. 配置通知
extension NotificationCenter.BaseName {
    /// 通知別名
    typealias Name = NotificationCenter.Name
    
    /// 名稱改變了
    static let nameChanged = Name<String>(name: "nameChanged")
}
  1. 發(fā)送與監(jiān)聽
/// 發(fā)送
NotificationCenter.post(.nameChanged , data: "新名稱")

/// 監(jiān)聽
NotificationCenter.notification(.nameChanged).subscribe(onNext: { [weak self] result in
            guard let self = self else { return }
            if let name = result.data {
                // ...
            }
        }).disposed(by: rx.disposeBag)

設(shè)計實現(xiàn)

  1. 首先是對數(shù)據(jù)模型的封裝, 數(shù)據(jù)模型使用泛型支持?jǐn)?shù)據(jù)類型
public extension NotificationCenter {
    /// 通知配置
    final class Name<T>: BaseName { }
    
    /// 通知配置
    class BaseName {
        
        /// 通知名稱
        public let name: String
        
        /// 自定義dataKey
        public let dataKey: String
        
        /// 初始化
        /// - Parameters:
        ///   - name: 通知名
        ///   - dataKey: 自定義dataKey,默認(rèn)為空吆寨,默認(rèn)為name
        public init(name: String, dataKey: String? = nil) {
            self.name = name
            self.dataKey = dataKey ?? name
        }
        
        /// 初始化
        /// - Parameters:
        ///   - name: 通知名
        ///   - dataKey: 自定義dataKey赏淌,默認(rèn)為空踩寇,默認(rèn)為name
        public init(name: NSNotification.Name, dataKey: String? = nil) {
            self.name = name.rawValue
            self.dataKey = dataKey ?? name.rawValue
        }
        
        /// 通知名
        var notificationName: NSNotification.Name {
            return NSNotification.Name(rawValue: name)
        }
    }
    
    /// 通知結(jié)果
    class NotificationResult<T> {
        /// 泛型數(shù)據(jù)
        let data: T?
        
        /// 通知全部數(shù)據(jù)
        let notification: Notification
        
        /// 通知來源
        var object: Any? {
            return notification.object
        }
        
        /// 通知信息
        var userInfo: [AnyHashable : Any]? {
            return notification.userInfo
        }
        
        /// 初始化
        /// - Parameters:
        ///   - data: 泛型數(shù)據(jù)
        ///   - notification: 通知數(shù)據(jù)
        init(data: T?, notification: Notification) {
            self.data = data
            self.notification = notification
        }
        
    }
}

  1. 發(fā)送通知和接收通知
public extension NotificationCenter {
    
    /// 發(fā)送通知
    /// - Parameters:
    ///   - name: 項目名稱配置
    ///   - data: 數(shù)據(jù)
    ///   - object: 發(fā)送源
    static func post<T>(_ name: Name<T>, data: T? = nil, object: Any? = nil) {
        var userInfo: [String: Any] = [:]
        if let data = data {
            userInfo[name.dataKey] = data
        }
        NotificationCenter.default.post(name: name.notificationName, object: object, userInfo: userInfo)
    }
    
    
    /// 監(jiān)聽通知
    /// - Parameter name: 項目名稱配置
    /// - Returns: 可見聽數(shù)據(jù)
    static func notification<T>(_ name: Name<T>) -> Observable<NotificationResult<T>> {
        NotificationCenter.default.rx.notification(name.notificationName).map { notify -> NotificationResult<T> in
            let userInfo = notify.userInfo
            let data = userInfo?[name.dataKey] as? T
            let result = NotificationResult.init(data: data, notification: notify)
            return result
        }
    }
    
    
    /// 發(fā)送通知(對象方法)
    /// - Parameters:
    ///   - name: 項目名稱配置
    ///   - data: 數(shù)據(jù)
    ///   - object: 發(fā)送源
    func post<T>(_ name: Name<T>, data: T? = nil, object: Any? = nil) {
        NotificationCenter.post(name, data: data, object: object)
    }
    
    /// 監(jiān)聽通知(對象方法)
    /// - Parameter name: 項目名稱配置
    /// - Returns: 可見聽數(shù)據(jù)
    func notification<T>(_ name: Name<T>) -> Observable<NotificationResult<T>> {
        return NotificationCenter.notification(name)
    }
    
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末啄清,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子俺孙,更是在濱河造成了極大的恐慌辣卒,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,657評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件睛榄,死亡現(xiàn)場離奇詭異荣茫,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)场靴,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,889評論 3 394
  • 文/潘曉璐 我一進(jìn)店門啡莉,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人旨剥,你說我怎么就攤上這事咧欣。” “怎么了轨帜?”我有些...
    開封第一講書人閱讀 164,057評論 0 354
  • 文/不壞的土叔 我叫張陵魄咕,是天一觀的道長。 經(jīng)常有香客問我蚌父,道長哮兰,這世上最難降的妖魔是什么毛萌? 我笑而不...
    開封第一講書人閱讀 58,509評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮喝滞,結(jié)果婚禮上阁将,老公的妹妹穿的比我還像新娘。我一直安慰自己囤躁,他們只是感情好冀痕,可當(dāng)我...
    茶點故事閱讀 67,562評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著狸演,像睡著了一般言蛇。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上宵距,一...
    開封第一講書人閱讀 51,443評論 1 302
  • 那天腊尚,我揣著相機(jī)與錄音,去河邊找鬼满哪。 笑死婿斥,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的哨鸭。 我是一名探鬼主播民宿,決...
    沈念sama閱讀 40,251評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼像鸡!你這毒婦竟也來了活鹰?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,129評論 0 276
  • 序言:老撾萬榮一對情侶失蹤只估,失蹤者是張志新(化名)和其女友劉穎志群,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體蛔钙,經(jīng)...
    沈念sama閱讀 45,561評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡锌云,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,779評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了吁脱。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片桑涎。...
    茶點故事閱讀 39,902評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖兼贡,靈堂內(nèi)的尸體忽然破棺而出攻冷,到底是詐尸還是另有隱情,我是刑警寧澤紧显,帶...
    沈念sama閱讀 35,621評論 5 345
  • 正文 年R本政府宣布讲衫,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏涉兽。R本人自食惡果不足惜招驴,卻給世界環(huán)境...
    茶點故事閱讀 41,220評論 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望枷畏。 院中可真熱鬧别厘,春花似錦、人聲如沸拥诡。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,838評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽渴肉。三九已至冗懦,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間仇祭,已是汗流浹背披蕉。 一陣腳步聲響...
    開封第一講書人閱讀 32,971評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留乌奇,地道東北人没讲。 一個月前我還...
    沈念sama閱讀 48,025評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像礁苗,于是被迫代替她去往敵國和親爬凑。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,843評論 2 354

推薦閱讀更多精彩內(nèi)容