Skip to content

Instantly share code, notes, and snippets.

@danielt1263
Created May 15, 2017 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielt1263/c7e464c9232ff9c4793371252da06a47 to your computer and use it in GitHub Desktop.
Save danielt1263/c7e464c9232ff9c4793371252da06a47 to your computer and use it in GitHub Desktop.
//
// DelayScheduler.swift
//
// Created by Daniel Tartaglia on 4/20/17.
// Copyright © 2017 Daniel Tartaglia. MIT License.
//
final class DelayScheduler: ImmediateSchedulerType {
init(delay: TimeInterval, queue: DispatchQueue = .main) {
self.queue = queue
dispatchDelay = delay
}
func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
let cancel = SingleAssignmentDisposable()
lastDispatch = max(lastDispatch + dispatchDelay, .now())
queue.asyncAfter(deadline: lastDispatch) {
guard cancel.isDisposed == false else { return }
cancel.setDisposable(action(state))
}
return cancel
}
private var lastDispatch: DispatchTime = .now()
private let queue: DispatchQueue
private let dispatchDelay: TimeInterval
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment