ios - 快速组合 : `first(_ n: Int)` equivalent to RxSwift `take(_ n: Int)` ?

标签 ios swift reactive-programming combine

我想要一个类似于 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 个元素之后完成。

最佳答案

关于ios - 快速组合 : `first(_ n: Int)` equivalent to RxSwift `take(_ n: Int)` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58647265/

相关文章:

ios - 默认突出显示表格 View 单元格未显示

ios - 如何在 Swift 中基本实现委托(delegate)?

ios - 应用程序是否可以禁止 iOS 8 中的自定义键盘?

swift - TableView 单元格 : Constraint change conflicts tableView. endUpdates()

c# - Reactive Extensions 中的 SequenceEqual 如何工作

ios - 无法在 iOS Appium 测试 (AWS Device Farm) 上切换到 WebView 上下文

iOS 按钮和导航链接在列表中彼此相邻

ios - "Zero out"Swift 中的敏感字符串数据

java - 如何使响应式@WebFilter与@RequestBody正常工作?

ios - Reactive Cocoa 在没有代码重复的情况下拆分信号?