So, how you handle with SearchBar typing too fast?

Mario tsai
4 min readDec 23, 2022

--

情境就是 每輸入一個字母,就打一次api,有沒有辦法優化?

  1. 最直覺就是用UI擋XD
  2. 記住搜尋過的結果

_____________________________以下是比較好的解法

3. 用Timer 做

4. 用線成控制 DispatchWorkItem

  • debounce 應該是這個情境下比較好的解法 程式碼如下
struct DispatchSemaphoreWrapper {
private var lock: DispatchSemaphore

init(value: Int) {
self.lock = DispatchSemaphore(value: value)
}

func sync(excute: () -> ()) {
_ = lock.wait(timeout: DispatchTime.distantFuture)
excute()
lock.signal()
}
}
class Debouncer {
private let label: String
private let interval: Int
private let queue: DispatchQueue
private var workItem: DispatchWorkItem?
private var lock: DispatchSemaphoreWrapper

/// interval: 毫秒
init(label: String = "Debouncer", interval: Int = 500) {
self.label = label
self.interval = interval
self.queue = DispatchQueue(label: label)
self.lock = DispatchSemaphoreWrapper(value: 1)
}

func call(_ callback: @escaping (() -> ())) {
self.lock.sync {
self.workItem?.cancel()
self.workItem = DispatchWorkItem {
callback()
}

if let workItem = self.workItem {
self.queue.asyncAfter(deadline: .now() + DispatchTimeInterval.milliseconds(interval), execute: workItem)
}
}
}
}

new 一個

let d = Debouncer.init(interval: 2000)

然後call api 放到 callback

d.call {
//your call
}

Fnish

--

--

Mario tsai
Mario tsai

Written by Mario tsai

Major in physical education. Football referee. And high interest in looking the world through the numbers.

No responses yet