Lợi ích của việc sử dụng DispatchWorkItem trong Swift là gì?

{{FormatNumbertoThousand(model.total_like)}} lượt thích
92 lượt xem
Swift master

Lớp DispatchWorkItem là sự đóng gói của khái niệm work-item. Bằng cách đóng gói mã yêu cầu của chúng ta trong một work-item, chúng ta có thể rất dễ dàng hủy bỏ nó bất cứ khi nào nó được thay thế bằng một item mới, như thế này:

class SearchViewController: UIViewController, UISearchBarDelegate {
   // We keep track of the pending work item as a property
   private var pendingRequestWorkItem: DispatchWorkItem?

   func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
      // Cancel the currently pending item
      pendingRequestWorkItem?.cancel()

      // Wrap our request in a work item
      let requestWorkItem = DispatchWorkItem { [weak self] in
         self?.resultsLoader.loadResults(forQuery: searchText)
      }

      // Save the new work item and execute it after 250 ms
      pendingRequestWorkItem = requestWorkItem
      DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(250),
            execute: requestWorkItem)
   }
}
{{login.error}}