Combine 框架,從0到1 —— 4.在 Combine 中使用通知

 

本文首發於 Ficow Shen’s Blog,原文地址: Combine 框架,從0到1 —— 4.在 Combine 中使用通知

 

內容概覽

  • 前言
  • 讓通知處理代碼使用 Combine
  • 總結

 

前言

 

通知中心是蘋果開發者常用的功能,很多框架都會使用通知中心來向外部發送異步事件。對於iOS開發人員而言,以下代碼一定非常眼熟:

var notificationToken: NSObjectProtocol?

override func viewDidLoad() {
    super.viewDidLoad()
	
    notificationToken = NotificationCenter.default
        .addObserver(forName: UIDevice.orientationDidChangeNotification,
                     object: nil,
                     queue: nil) { _ in
                        if UIDevice.current.orientation == .portrait {
                            print ("Orientation changed to portrait.")
                        }
    }
}

現在,讓我們來學習如何使用 Combine 處理通知,並將已有的通知處理代碼遷移到 Combine

 

讓通知處理代碼使用 Combine

 

使用通知中心回調和閉包要求您在回調方法或閉包內完成所有工作。通過遷移到 Combine,您可以使用操作符來執行常見的任務,如:filter

想充分利用 Combine,請使用 NotificationCenter.Publisher 將您的 NSNotification 處理代碼遷移到 Combine 習慣用法。您可以使用 NotificationCenter 方法 publisher(for:object:) 創建發佈者,並傳入您感興趣的通知名稱和可選的源對象。

var cancellable: Cancellable?

override func viewDidLoad() {
    super.viewDidLoad()
	
    cancellable = NotificationCenter.default
        .publisher(for: UIDevice.orientationDidChangeNotification)
        .filter() { _ in UIDevice.current.orientation == .portrait }
        .sink() { _ in print ("Orientation changed to portrait.") }
}

如上面的代碼所示,在 Combine 中重寫了最上面的代碼。此代碼使用了默認的通知中心來為orientationDidChangeNotification 通知創建發佈者。當代碼從該發佈者接收到通知時,它使用過濾器操作符 filter(_:) 來實現只處理縱向屏幕通知的需求,然後打印一條消息。

需要注意的是,orientationDidChangeNotification 通知的 userInfo 字典中不包含新的屏幕方向,因此 filter(_:) 操作符直接查詢了 UIDevice

 

總結

 

雖然上面的示例無法突顯 Combine 的優勢,但是我們可以自行想像。使用 Combine 之後,如果需求變得很複雜,我們要做的可能只是增加操作符而已,而且不破壞鏈式調用代碼的易讀性。

朋友,行動起來吧!把現有項目中的舊代碼重構成使用 Combine 的代碼~

 

本文內容來源:
Routing Notifications to Combine Subscribers

 

Tags: