title: How to prevent actor reentrancy resulting in duplicative requests?
body: <p>In WWDC 2021 video, <a href="https://developer.apple.com/videos/play/wwdc2021/10133/?time=720" rel="nofollow noreferrer">Protect mutable state with Swift actors</a>, they provide the following code snippet:</p>
  <pre class="lang-swift prettyprint-override"><code>actor ImageDownloader {
      private var cache: [URL: Image] = [:]
  
      func image(from url: URL) async throws -&gt; Image? {
          if let cached = cache[url] {
              return cached
          }
  
          let image = try await downloadImage(from: url)
  
          cache[url] = cache[url, default: image]
  
          return cache[url]
      }
  
      func downloadImage(from url: URL) async throws -&gt; Image { ... }
  }
  </code></pre>
  <p>The issue is that actors offer reentrancy, so <code>cache[url, default: image]</code> reference effectively ensures that even if you performed a duplicative request because of some race, that you at least check the actor’s cache after the continuation, ensuring that you get the same image for the duplicative request.</p>
  <p>And in that video, they <a href="https://developer.apple.com/videos/play/wwdc2021/10133/?time=720" rel="nofollow noreferrer">say</a>:</p>
  <blockquote>
  <p>A better solution would be to avoid redundant downloads entirely. We’ve put that solution in the code associated with this video.</p>
  </blockquote>
  <p>But there is no code associated with that video on the website. So, what is the better solution?</p>
  <p>I understand the benefits of actor reentrancy (as discussed in <a href="https://github.com/apple/swift-evolution/blob/main/proposals/0306-actors.md#actor-reentrancy" rel="nofollow noreferrer">SE-0306</a>). E.g., if downloading four images, one does not want to prohibit reentrancy, losing concurrency of downloads. We would, effectively, like to wait for the result of a duplicative prior request for a particular image if any, and if not, start a new <code>downloadImage</code>.</p>