去重序列异步流

去重序列异步流 通过增加元素去重功能,扩展了 AsyncStream 的概念。它不向消费者传递单独的更新,而是维护一个唯一元素的缓冲区,并将这些元素的序列传递给消费者。它要求生成的序列中的元素遵循 Hashable 协议。

安装

将包作为依赖项添加到你的项目中

.package(url: "https://github.com/supersonicbyte/deduplicated-sequence-async-stream", branch: "main")

瞧!就这样。

用法

使用静态 makeStream 方法或基于闭包的初始化器创建流。

struct StockPrice: Hashable {
    let symbol: String
    let price: Double

    func hash(into hasher: inout Hasher) {
        hasher.combine(symbol)
    }

    static func == (lhs: StockPrice, rhs: StockPrice) -> Bool {
        return lhs.symbol == rhs.symbol
    }
}

let (stream, continuation) = DeduplicatedSequenceAsyncStream.makeStream(of: StockPrice.self)

使用 continuation 来生成流中的值

continuation.yield(StockPrice(name: "AAPL", price: 120))
continuation.yield(StockPrice(name: "GOOGL", price: 230))

使用流的异步迭代器来消费流产生的序列

Task {
  for await prices in stream {
    print(prices)
  }
}

完成生产后,调用 continuation 的 finish() 方法来终止流。

continuation.finish()

使用 onTerminate() 回调来获得流终止时的通知

continuation.onTermination = { termination in 
  switch termination {
    case .finished:
      print("stream finished!")
    case .cancelled:
      print("stream cancelled!")
  }
}

有关用法的更多详细信息,请查阅文档。