Last active
March 28, 2022 04:53
-
-
Save onevcat/5c472446c721408afacea0793aa4ef2b to your computer and use it in GitHub Desktop.
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
```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