I need to use DispatchQueue within controller and pass it as dependency. This is what I have tried so far and worked out two solutions. Need to ask what is better and in common use by other developers:
protocol DispatchQueuerable: class {
func perform(withDelay delay: Double, block: @escaping () -> Void)
func performAsync(block: @escaping () -> Void)
}
First solution:
class DispatchQueuer: DispatchQueuerable {
private let queue: DispatchQueue
init(queue: DispatchQueue) {
self.queue = queue
}
func perform(withDelay delay: Double, block: @escaping () -> Void) {
queue.asyncAfter(deadline: .now() + delay as DispatchTime, execute: block)
}
func performAsync(block: @escaping () -> Void) {
queue.async {
block()
}
}
}
Second solution:
extension DispatchQueue: DispatchQueuerable {
func perform(withDelay delay: Double, block: @escaping () -> Void) {
asyncAfter(deadline: .now() + delay as DispatchTime, execute: block)
}
func performAsync(block: @escaping () -> Void) {
async {
block()
}
}
}
My question is what is better approach to avoid tight coupling in code and use MVVM Archtecture properly:
How do I use them?
First solution:
let queuer = DispatchQueuer(queue: DispatchQueue.main)
MyViewController(queuer: queuer)
class MyViewController: UIViewController {
private let queuer: DispatchQueuer
init(queuer: DispatchQueuer) {
self.queuer = queuer
}
}
Second solution:
let queue = DispatchQueue.main
MyViewController(queue: queue)
class MyViewController: UIViewController {
private let queue: DispatchQueue
init(queue: DispatchQueue) {
self.queue = queue
}
}
I really like the FIRST solution and know it, but what do you think about that?
DispatchQueuerable, rather than aDispatchQueueorDispatchQueuer. That is how you avoid tight coupling. Once you write your VC that way, either solution can be used with it.