sách gpt4 ai đã đi

ios - 组合:以一定的延迟发布序列的元素

In lại 作者:行者123 更新时间:2023-12-01 18:03:41 31 4
mua khóa gpt4 Nike

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

但在这种情况下,所有值都会立即打印出来。如何延迟打印值?在Combine 中有一个 .delay修饰符,但这不是我需要的(实际上, .delay 延迟了整个流而不是单个元素)。如果我尝试:
let publisherCanc = myCollection.publisher.delay(for: .seconds(0.5), scheduler: RunLoop.main).sink { value in
print(value)
}

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

谢谢你的帮助。

1 Câu trả lời

sử dụng answer 中的想法由 Alexander 链接在评论中,您可以使用 Timer.publish(every:on:in:) 创建每 0.5 秒发出一个值的发布者,然后 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) }

关于ios - 组合:以一定的延迟发布序列的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61212263/

31 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com