Uni*_*orn 6 publisher swift combine
我有一个发布者,当接收器时,扫描 wifi 列表。我只想扫描大约 10 秒然后停止。
有没有办法在发布者调用链中做到这一点?
这个操作符就能解决问题。
import PlaygroundSupport
import Foundation
import Combine
let page = PlaygroundPage.current
page.needsIndefiniteExecution = true
extension Publisher {
func stopAfter<S>(_ interval: S.SchedulerTimeType.Stride, tolerance: S.SchedulerTimeType.Stride? = nil, scheduler: S, options: S.SchedulerOptions? = nil) -> AnyPublisher<Output, Failure> where S: Scheduler {
prefix(untilOutputFrom: Just(()).delay(for: interval, tolerance: tolerance, scheduler: scheduler, options: nil))
.eraseToAnyPublisher()
}
}
let source = Timer.publish(every: 1, tolerance: nil, on: RunLoop.main, in: .default, options: nil)
.autoconnect()
.eraseToAnyPublisher()
let cancellable = source
.stopAfter(10, scheduler: DispatchQueue.main)
.sink(receiveValue: { print($0) })
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2591 次 |
| 最近记录: |