Skip to content

Instantly share code, notes, and snippets.

@jonahaung
Created November 6, 2019 02:03
Show Gist options
  • Save jonahaung/c18d3114f0a6f4101dd8e6459a74563d to your computer and use it in GitHub Desktop.
Save jonahaung/c18d3114f0a6f4101dd8e6459a74563d to your computer and use it in GitHub Desktop.
SerialTaskQueue
mport Foundation
public typealias TaskClosure = (_ completion: @escaping () -> Void) -> Void
public protocol SerialTaskQueueProtocol {
func addTask(_ task: @escaping TaskClosure)
func start()
func stop()
func flushQueue()
var isEmpty: Bool { get }
var isStopped: Bool { get }
}
public final class SerialTaskQueue: SerialTaskQueueProtocol {
public private(set) var isBusy = false
public private(set) var isStopped = true
private var tasksQueue = [TaskClosure]()
public init() {}
public func addTask(_ task: @escaping TaskClosure) {
self.tasksQueue.append(task)
self.maybeExecuteNextTask()
}
public func start() {
self.isStopped = false
self.maybeExecuteNextTask()
}
public func stop() {
self.isStopped = true
}
public func flushQueue() {
self.tasksQueue.removeAll()
}
public var isEmpty: Bool {
return self.tasksQueue.isEmpty
}
private func maybeExecuteNextTask() {
if !self.isStopped && !self.isBusy {
if !self.isEmpty {
let firstTask = self.tasksQueue.removeFirst()
self.isBusy = true
firstTask({ [weak self] () -> Void in
self?.isBusy = false
self?.maybeExecuteNextTask()
})
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment