Skip to content

Instantly share code, notes, and snippets.

@onevcat
Last active March 28, 2022 04:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onevcat/5c472446c721408afacea0793aa4ef2b to your computer and use it in GitHub Desktop.
Save onevcat/5c472446c721408afacea0793aa4ef2b to your computer and use it in GitHub Desktop.
```swift
actor GiftCache {
private(set) var cachedGifts: [GiftId: CachedGift] = [:]
// this method would be caller by other parts
func add(gift: CachedGift) {
cachedGifts[gift.giftId] = gift
//...
}
func cachedGift(of giftId: GiftId) throws -> CachedGift {
if let gift = cachedGifts[giftId] {
return gift
} else {
let gift = try load(giftId) // this is a synce operation
cachedGifts[giftId] = gift
return gift
}
}
}
public class GiftManager {
let cache = GiftCache()
private var unsafeCachedGifts: [GiftId: CachedGift] = [:]
@MainActor
public func refreshUnsafeCache() async {
self.unsafeCachedGifts = await cache.cachedGifts
}
public func unsafeDurationForGift(giftId: GiftId) -> TimeInterval {
dispatchPrecondition(condition: .onQueue(.main))
Task {
_ = try? await cache.cachedGift(of: giftId)
await refreshUnsafeCache()
}
let gift = unsafeCachedGifts[giftId]
return // ...
}
}
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment