# Swift concurrency: return cache and then load remote

**URL:** <https://forums.swift.org/t/swift-concurrency-return-cache-and-then-load-remote/71068>\
**Category:** Using Swift\
**Tags:** urlsession, asyncawait, cache\
**Created:** [April 3, 2024, 9:08pm UTC](https://forums.swift.org/t/swift-concurrency-return-cache-and-then-load-remote/71068 "2024-04-03T21:08:03Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![mhergon](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/mhergon/32/34793_2.png) [@mhergon](https://forums.swift.org/u/mhergon)\
**Post date:** [April 3, 2024, 9:08pm UTC](https://forums.swift.org/t/swift-concurrency-return-cache-and-then-load-remote/71068/1 "2024-04-03T21:08:03Z")

</div>

Hi,

Is there any way to return a value instantly and then reload the remote resources in an async/await call?  
I want to serve cached response, reload remote data and return on asynchronous call finish.

Is it possible?

Thanks!

---

<div class="post-metadata">

**Author:** ![Dmitriy\_Ignatyev](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dmitriy_ignatyev/32/11340_2.png) [@Dmitriy\_Ignatyev](https://forums.swift.org/u/Dmitriy_Ignatyev)\
**Post date:** [April 3, 2024, 9:20pm UTC](https://forums.swift.org/t/swift-concurrency-return-cache-and-then-load-remote/71068/2 "2024-04-03T21:20:20Z")

</div>

I see no blockers to do that. Something like:

```swift
func getValue(andUpdateIfNeeded updateCallback: @escaping (Value) -> Void) -> Value {
  let cachedValue = ...
  
  if isExpired(cachedValue) {
    makeRequest(completion: { newValue in
      updateCallback(newValue)
    }
  }

  return cachedValue
}

```

or

```swift
func getValue() -> (cachedValue: Value, updateIfNeeded: () async -> Value?) {
}

let (cachedValue, updateIfNeeded) = getValue()

// use cached value synchronously 

Task {
  let updatedValue = await updateIfNeeded()
  if let updatedValue {
    // ...
  }
}

```

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [April 3, 2024, 9:38pm UTC](https://forums.swift.org/t/swift-concurrency-return-cache-and-then-load-remote/71068/3 "2024-04-03T21:38:44Z")

</div>

I'd prefer the callback version with the callback which is called twice:

```swift
func getResource(url: URL, execute: @escaping (Data) -> Void) {
    let cachedResponse = ...
    execute(cachedResponse?.data)
    reload { execute($0) }
}

print("before")
getResource { data in
    print("got data")
}
print("after")

```

Outputs:

> [@](#):
>
> before  
> got data  
> after  
> got data

The async/await version of that could be done to make the use sites like so:

```swift
print("before")
for await data in url.asyncData {
    print("got data")
}
print("after")

```

with "got data" printed twice, first with cached data then with the new data after reload. Note that in this case the output would be:

> [@](#):
>
> before  
> got data  
> got data  
> after

---

<div class="post-metadata">

**Author:** ![mhergon](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/mhergon/32/34793_2.png) [@mhergon](https://forums.swift.org/u/mhergon)\
**Post date:** [April 3, 2024, 10:02pm UTC](https://forums.swift.org/t/swift-concurrency-return-cache-and-then-load-remote/71068/4 "2024-04-03T22:02:26Z")

</div>

Thanks @Dmitriy_Ignatyev and @tera

Looking at your suggestions, I think I've found the solution:

```swift
extension URLSession {
    
    func cachedDataAndReloadStream(for request: URLRequest) -> AsyncStream<(Data, URLResponse)> {
        
        AsyncStream<(Data, URLResponse)> { continuation in
            
            // Return cache
            if let cached = URLCache.shared.cachedResponse(for: request) {
                continuation.yield((cached.data, cached.response))
            }
            
            // Reload
            Task {
                
                let response = try await URLSession.shared.data(for: request)
                continuation.yield(response)
                continuation.finish()
                
            }
            
        }
        
    }
    
}

```

```swift
let request = makeRequest(baseURLString: "https://www.google.es")
for await response in URLSession.shared.cachedDataAndReloadStream(for: request) {
    
    // First cache, then reloaded
    
}

```
