hive中的combine_Swift的Combine中的ObservableObject协议是什么?

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:

结果,我们在控制台中看到两次打印“对象已更改”:

Image for post

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将自动更新:

Image for post

结语 (Wrapping Up)

Interested in other reactive techniques? Feel free to visit my other relevant articles:

对其他React技术感兴趣? 随时访问我的其他相关文章:

Thanks for reading!

谢谢阅读!

翻译自: https://medium.com/cleansoftware/what-is-the-observableobject-protocol-in-swifts-combine-b6ad3102ccd4

hive中的combine

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值