Swift 组合:`first(_ n: Int)` 相当于 RxSwift `take(_ n: Int)`?

Saj*_*jon 3 reactive-programming ios swift combine

我想要一个类似于 RxSwift 的组合运算符take(_ n: Int),我写了这个,它似乎有效:

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()
    }
}
Run Code Online (Sandbox Code Playgroud)

替代解决方案?

或者你能想出更好的替代解决方案吗?

(take但我将其命名为first,以反映合并本机运算符first- “发布流的第一个元素,然后完成。” ) 运算符在编写测试时非常方便,我希望发布者仅在n元素之后完成。