Swift 组合:`first(_ n: Int)` 等同于 RxSwift `take(_ n: Int)`?
Swift Combine: `first(_ n: Int)` equivalent to RxSwift `take(_ n: Int)`?
我想要一个类似于 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 { [=11=].publisher }.switchToLatest()
.eraseToAnyPublisher()
}
}
替代解决方案?
或者你能想出一个更好的替代解决方案吗?
take
(但我将其命名为 first
,以反映 Combine 本机运算符 first
- "Publishes the first element of a stream, then finishes.")运算符在编写测试时非常方便,我希望 Publisher 在 n
个元素之后完成。
在 Combine 中它被称为 prefix(_:)
。
https://developer.apple.com/documentation/combine/publisher/3204737-prefix
我想要一个类似于 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 { [=11=].publisher }.switchToLatest()
.eraseToAnyPublisher()
}
}
替代解决方案?
或者你能想出一个更好的替代解决方案吗?
take
(但我将其命名为 first
,以反映 Combine 本机运算符 first
- "Publishes the first element of a stream, then finishes.")运算符在编写测试时非常方便,我希望 Publisher 在 n
个元素之后完成。
在 Combine 中它被称为 prefix(_:)
。
https://developer.apple.com/documentation/combine/publisher/3204737-prefix