Learning & Refresh GCD Knowledge
After a year working as iOS developer, I'm usually confortable with reactive framework like RxSwift. But, I need to grasp again to basic knowledge about handling concurrency in iOS, using Grand Central Dispatch.
The most simple use case that I always use on RxSwift was debounce
function. It will cancel any prior execution before specified time passed. Imagine that we want to search something, we don't want to bombard our backend every we're typing the search query. That's debounce
come into play.
Then, i'll demonstrate how debounce works using GCD. Lets call our tiny helper as Debouncer
.
The following contracts when we're want to debounce as follows:
func debounce(
withInterval interval: TimeInterval,
handler: @escaping () -> Void,
queue: DispatchQueue
)
When we're bombard our debounce
call 100 times with interval 0.5 second, those handler
calls will be canceled. If there's no more debounce
call after 0.5 second, handler
will be executed afterwards.
So the final snippets will be as follows
class Debouncer {
private var workItem = DispatchWorkItem(block: {})
func debounce(
withInterval interval: TimeInterval,
handler: @escaping () -> Void,
queue: DispatchQueue
) {
workItem.cancel()
workItem = DispatchWorkItem(block: {
handler()
})
queue.asyncAfter(
deadline: .now() + interval,
execute: workItem
)
}
}