c++ combine使用
Consider this case: A specific screen in your app requires firing two different requests at the same time. Your goal is to update the UI only after both of them complete. In this tutorial, we will learn how to observe the completion of several network requests using Combine.
考虑这种情况:您应用中的特定屏幕需要同时触发两个不同的请求。 您的目标是仅在两个用户界面都完成后才对其进行更新。 在本教程中,我们将学习如何使用Combine观察几个网络请求的完成情况。
We will leverage a powerful .zip
operator that allows us to receive a tuple containing events from several upstream Publishers
.
我们将利用功能强大的.zip
运算符,该运算符使我们能够从多个上游Publishers
接收包含事件的元组。
In short, these are the topics you will master in this tutorial:
简而言之,这些是您将在本教程中掌握的主题:
Combine several
Publishers
using the.zip
operator.使用
.zip
运算符合并多个Publishers
者。Perform network requests using a built-in
URLSessionDataTask
publisher.使用内置的
URLSessionDataTask
发布器执行网络请求。Get transformed publishers using the
.map
operator with a key path.使用带有关键路径的
.map
运算符获取转换后的发布者。
The source code of the finished Xcode Playground is available at the bottom of the article.
本文底部提供了完成的Xcode Playground的源代码。
开始吧 (Let’s Start)
First, we need to import Combine
and create a subscriptions
property:
首先,我们需要导入Combine
并创建一个subscriptions
属性:
Now, let’s create a method that will fetch a random photo from Unsplash:
现在,让我们创建一个将从Unsplash获取随机照片的方法:
As we can see, Combine has a built-in publisher for URLSessionDataTask
.
如我们所见,Combine具有URLSessionDataTask
的内置发布URLSessionDataTask
。
Using the .map(keyPath:)
operator, we obtain Data
in just one line of code.
使用.map(keyPath:)
运算符,我们仅用一行代码即可获取Data
。
Then, in case any error happened during the request, we replace the error with an empty Data
object using the .replaceError
operator.
然后,如果在请求期间发生任何错误,我们将使用.replaceError
运算符将错误替换为空的Data
对象。
Finally, we erase the type of the publisher by using the .eraseToAnyPublisher
method.
最后,我们使用.eraseToAnyPublisher
方法删除发布者的类型。
Great! Now we can fetch a random photo from Unsplash. Let’s now add one more method that fetches the featured photo of the week:
大! 现在,我们可以从Unsplash获取随机照片。 现在让我们添加另一种获取本周特色照片的方法:
Now, our task is to fire these requests and be notified when both of them complete. By using the .zip
operator, we achieve what we want:
现在,我们的任务是触发这些请求,并在两个请求都完成时得到通知。 通过使用.zip
运算符,我们实现了我们想要的:
Note how in the .handleEvents
operator, we obtain a tuple containing two Data
objects: one from the randomPhotoPublisher
and another from the weeklyPhotoPublisher
.
请注意,在.handleEvents
运算符中,我们如何获得一个包含两个Data
对象的元组:一个来自randomPhotoPublisher
,另一个来自weeklyPhotoPublisher
。
If we run the playground, we will notice two images printed at the same time:
如果我们在操场上跑,我们会注意到同时打印了两个图像:
We have successfully observed the completion of several requests using Combine.
我们已经成功地观察到了使用Combine的几个请求的完成。
c++ combine使用