简体   繁体   English

Swift - 使用 NotificationCenter 来观察值变化真的很糟糕吗?

[英]Swift - Is using NotificationCenter to observe value change is really bad?

Just a beginner question.只是一个初学者的问题。 I hope someone can help me.我希望有一个人可以帮助我。 I am searching the best way to observe variable change globally in swift.我正在寻找快速观察全局变量变化的最佳方法。 And I encountered some article that says using NotificationCenter is a bad choice and we should avoid it as much as possible.我遇到了一些文章说使用 NotificationCenter 是一个糟糕的选择,我们应该尽可能避免它。 They are suggesting using delegates and dependency injection.他们建议使用委托和依赖注入。 I am using delagates for my reusable UI components.我正在为我的可重用 UI 组件使用 delegates。

But I have a websocket connection.但我有一个 websocket 连接。 I received data from this socket every second, this data are being used in different and multiple view controllers (4-6 VCs).我每秒都从这个套接字接收数据,这些数据被用于不同的多个视图控制器(4-6 个 VC)。 Right now, I am using NotificationCenter that notifies all these VCs when I received new data.现在,我正在使用 NotificationCenter 在收到新数据时通知所有这些 VC。

Is this the right approach or can you recommend me the correct way to do this?这是正确的方法还是你能推荐我正确的方法来做到这一点? Thank you.谢谢你。

Depending on the deployment target of your app, you could consider using Combine to propagate websocket events:根据您应用的部署目标,您可以考虑使用Combine来传播 websocket 事件:

The Combine framework provides a declarative Swift API for processing values over time. Combine 框架提供了一个声明性的 Swift API,用于随着时间的推移处理值。 These values can represent many kinds of asynchronous events.这些值可以表示多种异步事件。 Combine declares publishers to expose values that can change over time, and subscribers to receive those values from the publishers. Combine 声明发布者公开可以随时间变化的值,订阅者从发布者那里接收这些值。

https://developer.apple.com/documentation/combine https://developer.apple.com/documentation/combine

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM