Home > other >  How do you run a Swift Combine Publisher for a certain amount of time?
How do you run a Swift Combine Publisher for a certain amount of time?

Time:10-29

I have a publisher when the sink, scans for a list of wifi. I only want to scan for about 10 seconds and stop.

Is there a way to do this within the publisher chain of calls?

CodePudding user response:

There might be better ways, but throw this in a playground and try it out. It should get you started.

import Combine
import Foundation
import PlaygroundSupport

let page = PlaygroundPage.current
page.needsIndefiniteExecution = true

func example(source: AnyPublisher<Date, Never>) -> AnyPublisher<Date, Never> {
    source
        .prefix(untilOutputFrom: Timer.publish(every: 10, tolerance: nil, on: RunLoop.main, in: .default, options: nil).autoconnect())
        .eraseToAnyPublisher()
}

let source = Timer.publish(every: 1, tolerance: nil, on: RunLoop.main, in: .default, options: nil)
    .autoconnect()
    .eraseToAnyPublisher()

let cancellable = example(source: source)
    .sink(receiveValue: { print($0) })

You could put a prefix(1) on the ten second timer, but it isn't necessary. The timer will shut down after the prefix(untilOutputFrom:) completes.

  • Related