【问题标题】:Swift Combine: Collect with Sliding window like functionalitySwift Combine:使用类似滑动窗口的功能进行收集
【发布时间】:2021-02-15 00:33:07
【问题描述】:

所以我有这个联合发布者说发出整数 - 1,2,3,4,5,6,7,8,9,10,11 ....

这些整数虽然并不总是存在。它们是即时生成并发送给发布者的。

我知道 collect 运算符,当它被称为 .collect(5) 时给了我 - [1,2,3,4,5], [6,7,8,9,10], ...

我正在寻找的东西有点像缓冲区和收集组合 - [1,2,3,4,5], [2,3,4,5,6], [3,4,5,6,7] ...。

有什么方法可以在不编写自定义运算符的情况下做到这一点?如果自定义运算符是要走的路,你能提供一些指导吗,我以前没有写过自定义运算符。我希望从示例中可以清楚地了解我的要求。

谢谢

编辑

这可行,但我不确定这是否是最佳解决方案 -

publisher.zip(
    publisher.dropFirst(),
    publisher.dropFirst(2))

【问题讨论】:

    标签: swift combine


    【解决方案1】:

    您可以使用scan 运算符来实现此效果。 Scan 使您能够累积一个值——在这种情况下是一个先前值的数组——然后发出它。您只需要删除最初的 N-1 个较小的数组。

    为方便起见,您可以创建自定义运算符sliding(window:):

    extension Publisher {
        func sliding(window: Int) -> AnyPublisher<[Output], Failure> {
            if window < 1 { return Empty().eraseToAnyPublisher() }
            return self
               .scan([], { arr, value in
                   if arr.count < window {
                       return arr + [value]
                   } else {
                       return arr.dropFirst() + [value]
                   }
               })
               .dropFirst(window - 1)
               .eraseToAnyPublisher()
       }
    }
    

    用法是:

    [1,2,3,4,5,6,7,8,9,10].publisher
       .sliding(window: 5)
       .sink { 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]
    

    【讨论】:

      【解决方案2】:

      如果您确定您的发布者总是发出至少 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]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-22
        • 2018-05-10
        • 2014-07-05
        • 2019-12-25
        • 2021-06-22
        • 2011-10-29
        相关资源
        最近更新 更多