如果您确定您的发布者总是发出至少 N 个元素(N 是窗口大小),那么 New Dev 提供的解决方案就可以正常工作。
但是如果你想涵盖所有情况,那么事情就会变得更加复杂,因为没有简单的方法来拥有滑动窗口,同时如果它们不足以填满窗口,仍然保留第一个元素。
一种可能的解决方案涉及更长、更复杂的运算符管道,如下所示:
extension Publisher {
func sliding(window count: Int) -> AnyPublisher<[Output], Failure> {
self
// 1. collect batches of the given size
.collect(count)
// 2. we need to retain the last two batches, to be able to detect the case
// where we have only one batch, that could be smaller than the window size
.scan(([], [])) { ($0.1, $1) }
// 3. now that the publisher emitted batches, we either publish the last batch
// if we have only one, or we generate an array of batches by appending elements
// from the last batch into the second last one
.map { secondLast, last in secondLast.isEmpty ? [last] : last.indices.map { secondLast + last[...$0] } }
// 4. now that we have an array of batches, we need to flatten them, and
// for this we use MergeMany over an array of Just() publishers created from the batches
.flatMap { Publishers.MergeMany($0.map(Just.init)).setFailureType(to: Failure.self) }
// 5. now we only keep the N elements from the batch
// we could've done this at step 3, however that would've complicate that step even more
.map { $0.suffix(count) }
// 6. and, done :)
.eraseToAnyPublisher()
}
}
用法
_ = (1...4).publisher
.sliding(window: 5)
.sink(receiveValue: { print($0) })
// [1, 2, 3, 4]
_ = (1...10).publisher
.sliding(window: 5)
.sink(receiveValue: { print($0) })
// [1, 2, 3, 4, 5]
// [2, 3, 4, 5, 6]
// [3, 4, 5, 6, 7]
// [4, 5, 6, 7, 8]
// [5, 6, 7, 8, 9]
// [6, 7, 8, 9, 10]