Swift 5 Combine 和 NotificationCenter 結合使用
NotificationCenter
通常使用 需要先注冊addObserver 再監聽發布通知 post 還要與addObserver 成對出現 removeObserver
現在結合Combine 在注冊通知時候可以寫成數據流式
1 構建發布者publisher,數據流式返回訂閱者refreshColorSub
private var refreshColorSub: AnyCancellable? extension HomeVC { func bindColorSub() { refreshColorSub = NotificationCenter.default.publisher(for: NSNotification.Name(rawValue: ThemeModeChangedNotiKey)) .receive(on: RunLoop.main) .sink {[weak self] _ in //??弱引用 否則頁面無法銷毀 self?.refreshTraitColor() } } }
2 修改顏色時候發出通知Post
NotificationCenter.default.post(name: NSNotification.Name(rawValue: ThemeModeChangedNotiKey), object: nil)
3 ??Publisher利用了swift的可選類型特點 無需移除 removeObserver
參考
1 https://www.it610.com/article/1294863452317229056.htm
posted on 2021-03-24 15:10 ACM_Someone like you 閱讀(559) 評論(0) 收藏 舉報
浙公網安備 33010602011771號