From 46407f925dee7346cbb617fa4657dda9433f1f15 Mon Sep 17 00:00:00 2001 From: DreamPiggy Date: Wed, 6 Nov 2024 14:27:51 +0800 Subject: [PATCH] Fix the data race because progress block is called in non-main queue This match the behavior of `progress indicator`, which only update on main queue Note: This is different behavior compared to SDWebIamge on UIKit (progress updated in global queue) --- SDWebImageSwiftUI/Classes/ImageManager.swift | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/SDWebImageSwiftUI/Classes/ImageManager.swift b/SDWebImageSwiftUI/Classes/ImageManager.swift index 7da6fc9..045bfa3 100644 --- a/SDWebImageSwiftUI/Classes/ImageManager.swift +++ b/SDWebImageSwiftUI/Classes/ImageManager.swift @@ -85,6 +85,7 @@ public final class ImageManager : ObservableObject { self.indicatorStatus.isLoading = true self.indicatorStatus.progress = 0 currentOperation = manager.loadImage(with: url, options: options, context: context, progress: { [weak self] (receivedSize, expectedSize, _) in + // This block may be called in non-main thread guard let self = self else { return } @@ -95,7 +96,11 @@ public final class ImageManager : ObservableObject { progress = 0 } self.indicatorStatus.progress = progress - self.progressBlock?(receivedSize, expectedSize) + if let progressBlock = self.progressBlock { + DispatchQueue.main.async { + progressBlock(receivedSize, expectedSize) + } + } }) { [weak self] (image, data, error, cacheType, finished, _) in guard let self = self else { return