Clean up progress logic

This commit is contained in:
ronaldheft
2022-08-08 17:21:13 -04:00
parent 948cd3068a
commit 8e2be4704e
+19 -23
View File
@@ -106,38 +106,34 @@ public class AbsDownloader: CAPPlugin, URLSessionDownloadDelegate {
self.progressStatusWorkItem = DispatchWorkItem { [weak self] in self.progressStatusWorkItem = DispatchWorkItem { [weak self] in
// Clean up the work item when done // Clean up the work item when done
defer { self?.progressStatusWorkItem = nil } defer { self?.progressStatusWorkItem = nil }
var downloadItemProgress = [String: DownloadItem]()
// Get the latest progress // Fetch active downloads in a thread-safe way
self?.progressStatusQueue.sync { func fetchActiveDownloads() -> [String: DownloadItem]? {
if let progressItems = self?.downloadItemProgress { self?.progressStatusQueue.sync { self?.downloadItemProgress }
downloadItemProgress = progressItems }
// Remove a completed download item in a thread-safe way
func handleDoneDownloadItem(_ item: DownloadItem) {
self?.progressStatusQueue.async(flags: .barrier) {
defer {
Database.shared.removeDownloadItem(item)
self?.downloadItemProgress.removeValue(forKey: item.id!)
}
self?.handleDownloadTaskCompleteFromDownloadItem(item)
} }
} }
while !downloadItemProgress.isEmpty { // While there are active download items, emit status updates
for item in downloadItemProgress.values { while !(fetchActiveDownloads()?.isEmpty ?? false) {
try? self?.notifyListeners("onItemDownloadUpdate", data: item.asDictionary()) if let activeDownloads = fetchActiveDownloads() {
for item in activeDownloads.values {
// Clean up a completed download try? self?.notifyListeners("onItemDownloadUpdate", data: item.asDictionary())
if item.isDoneDownloading() { if item.isDoneDownloading() { handleDoneDownloadItem(item) }
self?.progressStatusQueue.async(flags: .barrier) {
self?.downloadItemProgress.removeValue(forKey: item.id!)
}
defer { Database.shared.removeDownloadItem(item) }
self?.handleDownloadTaskCompleteFromDownloadItem(item)
} }
} }
// Wait 200ms before reporting status again // Wait 200ms before reporting status again
Thread.sleep(forTimeInterval: TimeInterval(0.2)) Thread.sleep(forTimeInterval: TimeInterval(0.2))
// Get the latest progress
self?.progressStatusQueue.sync {
if let progressItems = self?.downloadItemProgress {
downloadItemProgress = progressItems
}
}
} }
} }