首页 > 解决方案 > 组合:以一定的延迟发布序列的元素

问题描述

我是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)
}

我得到的只是“初始”延迟,然后立即打印元素。

谢谢你的帮助。

标签: iosswiftcombine

解决方案


使用Alexander在评论中链接的答案中的想法,您可以创建一个发布者,该发布者使用 0.5 秒发出一个值,然后与您一起使您的下游发布者在每次您的两个发布者都发出一个新值时发出一个值.Timer.publish(every:on:in:)zipArray.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) }

推荐阅读