Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Wrapper around `DispatchQueue` of iOS to make it easier to inject it in systems under testing. Referenced in <Link>.
final public class AsyncQueueDispatcher: Dispatcher {
private let queue: DispatchQueue
public init(queue: DispatchQueue) {
self.queue = queue
}
public func dispatch(_ work: @escaping ()->Void) {
queue.async(execute: work)
}
public func dispatch(execute workItem: DispatchWorkItem) {
queue.async(execute: workItem)
}
public func dispatchAfter(deadline: DispatchTime, _ work: @escaping () -> Void) {
queue.asyncAfter(deadline: deadline, execute: work)
}
public func dispatchAfter(deadline: DispatchTime, execute workItem: DispatchWorkItem) {
queue.asyncAfter(deadline: deadline, execute: workItem)
}
}
/// Adding convenience access to common `DispatchQueue`s wrapped with `AsyncQueueDispatcher`
public extension AsyncQueueDispatcher {
static let main = AsyncQueueDispatcher(queue: .main)
static let global = AsyncQueueDispatcher(queue: .global())
static let background = AsyncQueueDispatcher(queue: .global(qos: .background))
}
public protocol Dispatcher {
func dispatch(_ work: @escaping ()->Void)
func dispatch(execute workItem: DispatchWorkItem)
func dispatchAfter(deadline: DispatchTime, _ work: @escaping ()->Void)
func dispatchAfter(deadline: DispatchTime, execute workItem: DispatchWorkItem)
}
final public SyncQueueDispatcher: Dispatcher {
private let queue: DispatchQueue
public init(queue: DispatchQueue) {
self.queue = queue
}
public func dispatch(_ work: @escaping ()->Void) {
queue.sync(execute: work)
}
public func dispatch(execute workItem: DispatchWorkItem) {
queue.sync(execute: workItem)
}
public func dispatchAfter(deadline: DispatchTime, _ work: @escaping () -> Void) {
// Calling asyncAfter on a "sync queue" is wrong, but will be handled as a sync task normally
queue.sync(execute: work)
}
public func dispatchAfter(deadline: DispatchTime, execute workItem: DispatchWorkItem) {
queue.sync(execute: workItem)
}
}
/// Adding convenience access to common `DispatchQueue`s wrapped with `SyncQueueDispatcher`
public extension SyncQueueDispatcher {
static let global = SyncQueueDispatcher(queue: .global())
static let background = SyncQueueDispatcher(queue: .global(qos: .background))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment