Skip to content

Instantly share code, notes, and snippets.

@ATahhan
Last active April 25, 2022 21:12
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save ATahhan/9293e913c5907d8442d71343602fea13 to your computer and use it in GitHub Desktop.
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