Last active
October 30, 2022 07:37
-
-
Save Mr-Alirezaa/1e54ec53d0a566fa1b24414e60727bc2 to your computer and use it in GitHub Desktop.
This is an example of using swift actor type to handle downloading of images from URLs and avoid problems caused by "Actor Reentrancy".
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // See: https://stackoverflow.com/a/70595187/8249180 | |
| actor ImageDownloader { | |
| private enum CacheEntry { | |
| case inProgress(Task<Image, Error>) | |
| case ready(Image) | |
| } | |
| private var cache: [URL: CacheEntry] = [:] | |
| func image(from url: URL) async throws -> Image? { | |
| if let cached = cache[url] { | |
| switch cached { | |
| case .ready(let image): | |
| return image | |
| case .inProgress(let task): | |
| return try await task.value | |
| } | |
| } | |
| let task = Task { | |
| try await downloadImage(from: url) | |
| } | |
| cache[url] = .inProgress(task) | |
| do { | |
| let image = try await task.value | |
| cache[url] = .ready(image) | |
| return image | |
| } catch { | |
| cache[url] = nil | |
| throw error | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment