我想要一个类似于 RxSwift 的 take(_ n: Int)
的 Combine 运算符,我写了这个,它似乎有效:
first(_ n)
实现
public extension Publisher where Failure == Never {
/// Publishes the first `n` elements of a stream, then finishes.
func first(_ numberOfElements: Int) -> AnyPublisher<Output, Failure> {
collect(numberOfElements) // "Buffer"
.first() // "release and complete (finish)"
// Publisher<[Output]> -> Publisher<Output>
.map { $0.publisher }.switchToLatest()
.eraseToAnyPublisher()
}
}
替代方案?
或者您能想出一个更好的替代解决方案吗?
take
(但我将其命名为 first
,以反射(reflect) Combine native 运算符 first
- “发布流的第一个元素,然后完成.") 运算符在编写测试时非常方便,我希望 Publisher 在 n
个元素之后完成。
最佳答案
在 Combine 中它被称为 prefix(_:)
。
https://developer.apple.com/documentation/combine/publisher/3204737-prefix
关于ios - 快速组合 : `first(_ n: Int)` equivalent to RxSwift `take(_ n: Int)` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58647265/