Created
November 6, 2019 02:03
-
-
Save jonahaung/c18d3114f0a6f4101dd8e6459a74563d to your computer and use it in GitHub Desktop.
SerialTaskQueue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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