Clean up progress logic

This commit is contained in:
ronaldheft
2022-08-08 17:21:13 -04:00
parent 948cd3068a
commit 8e2be4704e
+16 -20
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
}
} }
while !downloadItemProgress.isEmpty { // Remove a completed download item in a thread-safe way
for item in downloadItemProgress.values { func handleDoneDownloadItem(_ item: DownloadItem) {
try? self?.notifyListeners("onItemDownloadUpdate", data: item.asDictionary())
// Clean up a completed download
if item.isDoneDownloading() {
self?.progressStatusQueue.async(flags: .barrier) { self?.progressStatusQueue.async(flags: .barrier) {
defer {
Database.shared.removeDownloadItem(item)
self?.downloadItemProgress.removeValue(forKey: item.id!) self?.downloadItemProgress.removeValue(forKey: item.id!)
} }
defer { Database.shared.removeDownloadItem(item) }
self?.handleDownloadTaskCompleteFromDownloadItem(item) self?.handleDownloadTaskCompleteFromDownloadItem(item)
} }
} }
// While there are active download items, emit status updates
while !(fetchActiveDownloads()?.isEmpty ?? false) {
if let activeDownloads = fetchActiveDownloads() {
for item in activeDownloads.values {
try? self?.notifyListeners("onItemDownloadUpdate", data: item.asDictionary())
if item.isDoneDownloading() { handleDoneDownloadItem(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
}
}
} }
} }