hive中的combine
Conforming to the ObservableObject
protocol provides a handy way to monitor when one of its @Published
properties change. However, we can’t know which exact property has changed. It is created to help you when using SwiftUI in your projects.
符合ObservableObject
协议提供了一种方便的方法来监视其@Published
属性之一@Published
更改。 但是,我们不知道哪个确切的属性已更改。 创建它是为了在项目中使用SwiftUI时为您提供帮助。
Without a further ado, let’s explore the ObservableObject
protocol in practice.
事不宜迟,让我们在实践中探索ObservableObject
协议。
开始吧 (Let’s Start)
Say we have a simple class called ObjectToBeObserved
:
假设我们有一个名为ObjectToBeObserved
的简单类:
What if we want to be notified when its value property is changed? We can conform to the ObservableObject
and mark the value
property with a Published
property wrapper:
如果我们想在其value属性更改时收到通知怎么办? 我们可以遵循ObservableObject
并用Published
属性包装器标记value
属性:
Behind the scenes, the objectWillChange
publisher is created, which we will use now to observe for changes:
在幕后,创建了objectWillChange
发布者,我们现在将使用它来观察更改:
We can now test the implementation by assigning a new value to the value
property:
现在,我们可以通过为value
属性分配一个新值来测试实现:
As a result, we see the “Object has changed” printed two time in the console:
结果,我们在控制台中看到两次打印“对象已更改”:
Now you may think, why didn’t we simply use the Published
property wrapper and subscribe to it? As I said in the beginning the ObservableObject
protocol is designed to work with SwiftUI.
现在您可能会想,为什么我们不简单地使用Published
属性包装器并对其进行订阅? 正如我在一开始所说的, ObservableObject
协议旨在与SwiftUI一起使用。
Let’s explore how we use it with SwiftUI now. Here is our original ObjectToBeObserved
:
让我们探讨一下我们现在如何在SwiftUI中使用它。 这是我们原始的ObjectToBeObserved
:
Now let’s create a View
:
现在让我们创建一个View
:
Now the Text
is automatically updated when the value property of the ObjectToBeObserved
changes:
现在,当ObjectToBeObserved
的value属性更改时, Text
将自动更新:
结语 (Wrapping Up)
Interested in other reactive techniques? Feel free to visit my other relevant articles:
对其他React技术感兴趣? 随时访问我的其他相关文章:
Thanks for reading!
谢谢阅读!
hive中的combine