Updated 4 July 2023
Throttling is mainly used for the searching tasks whenever a user types fast to make sure that, backend server doesn’t receive multiple requests. if you send multiple requests to the server and canceling the request it increases the load on the server if the server is paid and it also increases the cost too much.
Best way to implement is throttler by using the RxSwift but the question is for the single task why you use RxSwift the better way you can use the GCD for this.
For implementing throttler you can use the DispatchWorkItem from this you can set a pause to the request or on a task and cancel the previous task. Check the implementation of throttler:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class Throttler { private var searchTask: DispatchWorkItem? deinit { print("Throttler object deiniantialized") } func throttle(searchText: String, block: @escaping (_ products: [ProductData]) -> Void) { searchTask?.cancel() let task = DispatchWorkItem { [weak self] in guard let obj = self else { return } // obj.getSearchProducts(searchText: searchText) { (products) in // block(products) // } // here you hit the request and get back the data } self.searchTask = task DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5, execute: task) } } |
How to use it:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
private var throttler: Throttler? /// Event received when a change into the search box is occurred override func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { defer { self.throttler?.throttle(searchText: searchText) { [weak self] (products) in self?.throttler = nil self?.delegate?.shareSearchData(products: products) } } guard self.throttler != nil else { self.throttler = Throttler() return } } |
I hope from this, it will make you more comfortable dealing with Throttling calls. Thanks for tuning in once again!
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.