ios - 组合:以一定的延迟发布序列的元素
问题描述
我是Combine 的新手,我想得到一个看似简单的东西。假设我有一个整数集合,例如:
let myCollection = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
我想以例如 0.5 秒的延迟发布每个元素。
print 0
wait for 0.5secs
print 1
wait for 0.5secs
and so forth
我可以轻松获取序列发布者并打印如下元素:
let publisherCanc = myCollection.publisher.sink { value in
print(value)
}
但在这种情况下,所有值都会立即打印出来。如何延迟打印值?在组合中有一个.delay
修饰符,但它不是我需要的(实际上,.delay
延迟了整个流而不是单个元素)。如果我尝试:
let publisherCanc = myCollection.publisher.delay(for: .seconds(0.5), scheduler: RunLoop.main).sink { value in
print(value)
}
我得到的只是“初始”延迟,然后立即打印元素。
谢谢你的帮助。
解决方案
使用Alexander在评论中链接的答案中的想法,您可以创建一个发布者,该发布者使用 0.5 秒发出一个值,然后与您一起使您的下游发布者在每次您的两个发布者都发出一个新值时发出一个值.Timer.publish(every:on:in:)
zip
Array.publisher
Publishers.Zip
获取其上游发布者的第 n 个元素,并且仅在其两个上游发布者都达到 n 个发出值时才发出 - 因此,通过将仅以0.5 second
间隔发出其值的发布者与立即发出其所有值的原始发布者压缩在一起,您将每个值延迟 0.5 秒。
let delayPublisher = Timer.publish(every: 0.5, on: .main, in: .default).autoconnect()
let delayedValuesPublisher = Publishers.Zip(myCollection.publisher, delayPublisher)
let subscription = delayedValuesPublisher.sink { print($0.0) }
推荐阅读
- sql - 如何根据指标列值的变化获取组 row_number()?
- java - 如何仅针对谷歌应用引擎中的特定请求路径处理并发?
- python-3.x - 您如何为错误的用户输入编写错误消息?
- css - 为固定/“粘性”菜单调整网站的整个上部区域
- ios - 音乐信息显示在命令中心但不显示锁定屏幕
- amazon-web-services - ClientError:使用地面实况图像的 AWS object_detection_augmented_manifest_training 未指定训练通道
- mysql - 如何在没有通用“GROUP BY”元素的情况下组合来自 2 个查询的结果
- php - PHP 图像调整大小和展开占位符(透明)
- twitter-bootstrap - XPages 中的 bootstrapValidator
- android - 如何清理这些复杂的按钮?