Skip to content

Instantly share code, notes, and snippets.

@Mr-Alirezaa
Last active October 30, 2022 07:37
Show Gist options
  • Select an option

  • Save Mr-Alirezaa/1e54ec53d0a566fa1b24414e60727bc2 to your computer and use it in GitHub Desktop.

Select an option

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".
// 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