如何运行 Swift Joint Publisher 一段时间?

Uni*_*orn 6 publisher swift combine

我有一个发布者,当接收器时,扫描 wifi 列表。我只想扫描大约 10 秒然后停止。

有没有办法在发布者调用链中做到这一点?

Dan*_* T. 8

这个操作符就能解决问题。

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)

  • 超时发布者可以简化为“Just(1).delay(for: 10, Scheduler: DispatchQueue.main)” (2认同)
  • @Cristik 感谢您的改进。我也像您一样将该函数包装在一个新的运算符中。 (2认同)