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

原文地址:https://www.cnblogs.com/someonelikeyou/p/14573647.html