?
本文首發(fā)于 Ficow Shen's Blog,原文地址: Combine 框架,從0到1 —— 4.在 Combine 中使用通知。
?
內(nèi)容概覽
- 前言
- 讓通知處理代碼使用 Combine
- 總結(jié)
?
前言
?
通知中心是蘋果開發(fā)者常用的功能,很多框架都會(huì)使用通知中心來向外部發(fā)送異步事件。對(duì)于iOS開發(fā)人員而言,以下代碼一定非常眼熟:
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.")
}
}
}
現(xiàn)在,讓我們來學(xué)習(xí)如何使用 Combine 處理通知,并將已有的通知處理代碼遷移到 Combine。
?
讓通知處理代碼使用 Combine
?
使用通知中心回調(diào)和閉包要求您在回調(diào)方法或閉包內(nèi)完成所有工作。通過遷移到 Combine,您可以使用操作符來執(zhí)行常見的任務(wù),如:filter。
想充分利用 Combine,請(qǐng)使用 NotificationCenter.Publisher 將您的 NSNotification 處理代碼遷移到 Combine 習(xí)慣用法。您可以使用 NotificationCenter 方法 publisher(for:object:) 創(chuàng)建發(fā)布者,并傳入您感興趣的通知名稱和可選的源對(duì)象。
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 中重寫了最上面的代碼。此代碼使用了默認(rèn)的通知中心來為orientationDidChangeNotification 通知?jiǎng)?chuàng)建發(fā)布者。當(dāng)代碼從該發(fā)布者接收到通知時(shí),它使用過濾器操作符 filter(_:) 來實(shí)現(xiàn)只處理縱向屏幕通知的需求,然后打印一條消息。
需要注意的是,orientationDidChangeNotification 通知的 userInfo 字典中不包含新的屏幕方向,因此 filter(_:) 操作符直接查詢了 UIDevice。
?
總結(jié)
?
雖然上面的示例無法突顯 Combine 的優(yōu)勢,但是我們可以自行想象。使用 Combine 之后,如果需求變得很復(fù)雜,我們要做的可能只是增加操作符而已,而且不破壞鏈?zhǔn)秸{(diào)用代碼的易讀性。
朋友,行動(dòng)起來吧!把現(xiàn)有項(xiàng)目中的舊代碼重構(gòu)成使用 Combine 的代碼~
?
推薦繼續(xù)閱讀:Combine 框架,從0到1 —— 4.在 Combine 中使用計(jì)時(shí)器
?
本文內(nèi)容來源:
Routing Notifications to Combine Subscribers
?