Skip to content

how would i create a Timer signal #25

@jpmhouston

Description

@jpmhouston

Any tips for creating a timer signal? Here's what I tried throwing together based on examples and a gesture recognizer signal I made that does work, but it doesn't fire.

public extension Signal {
    // in case of a Timer, we dont start with an object on which we bootstrap a signal
    // so add this class method on Signal itself for creating a timer signal (can we make this a convenience init instead?)
    public class func repeatingTimer(withInterval interval: TimeInterval) -> Signal<Timer> {
        let signal = Signal<Timer>()
        let observer = IntervalTimerOperator(interval: interval)
        
        observer.callback = { [weak signal] timer in
            signal?.send(timer)
        }
        
        signal.disposableSource = observer
        
        return signal
    }
}

final class IntervalTimerOperator: NSObject, Disposable {
    private var timer: Timer!
    private var isDisposed = false
    
    internal var callback: ((_ timer: Timer) -> Void)?
    
    init(interval: TimeInterval, repeats: Bool = true) {
        super.init()
        self.timer = Timer(timeInterval: interval, target: self, selector: #selector(fire(_:)), userInfo: nil, repeats: repeats)
    }
    
    func fire(_: Timer) {
        callback?(timer)
    }
    
    func dispose() {
        guard !isDisposed else { return }
        timer.invalidate()
        isDisposed = true
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions