c++ combine使用
In this article, we will learn how to make our Swift code more distinctive and efficient by using Combine.
在本文中,我们将学习如何通过使用Combine使我们的Swift代码更具特色和效率。
Without further ado, let’s get started.
事不宜迟,让我们开始吧。
开始吧 (Let’s Start)
If you ever needed to observe for keyboard events, then this code probably looks very familiar:
如果您需要观察键盘事件,那么此代码可能看起来非常熟悉:
Once we receive the keyboardWillShowNotification
, we simply print a message in the console. By using Combine, we can make the code more succinct without needing to pass those nil
values as parameters:
一旦收到keyboardWillShowNotification
,我们只需在控制台中打印一条消息。 通过使用Combine,我们可以使代码更加简洁,而无需将这些nil
值作为参数传递:
To write an asynchronous logic, you would usually include an escaping closure as a parameter:
要编写异步逻辑,通常将转义的闭包作为参数包括在内:
You can use the Combine’s future instead:
您可以改为使用合并的未来:
With this approach, you would be able to use a variety of Combine operators to transform or filter your data. Moreover, you could use the .assign
operator to bind the result to a property.
使用这种方法,您将能够使用各种组合运算符来转换或过滤数据。 此外,您可以使用.assign
运算符将结果绑定到属性。
Before Combine, you would write something like this to create a simple repeating timer:
在合并之前,您将编写如下代码来创建一个简单的重复计时器:
With a Combine publisher, you make it look better:
使用Combine发行商,您可以使它看起来更好:
As a result, we see each second printed in the console:
结果,我们看到每秒在控制台中打印:
When following the MVVM design pattern, you would create closure properties to be invoked every time a given asynchronous event occurs:
当遵循MVVM设计模式时,您将创建每次给定异步事件发生时都会调用的闭包属性:
Let’s use Combine’s PassthroughSubject
instead:
让我们改用Combine的PassthroughSubject
:
We see that after three seconds, a message is printed:
我们看到三秒钟后,将显示一条消息:
结语 (Wrapping Up)
Interested in more Combine features? My other articles may be helpful to you:
对更多合并功能感兴趣? 我的其他文章可能对您有所帮助:
Thanks for reading!
谢谢阅读!
翻译自: https://medium.com/better-programming/use-combine-to-write-more-readable-swift-code-9e8e6cf0bf50
c++ combine使用