Files
purchases-ios/Sources/Caching/InMemoryCachedObject.swift
T

69 lines
1.7 KiB
Swift
Raw Normal View History

2021-07-20 09:21:53 -07:00
//
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
2021-07-20 09:21:53 -07:00
// InMemoryCachedObject.swift
//
// Created by Joshua Liebowitz on 7/13/21.
//
import Foundation
class InMemoryCachedObject<T> {
2021-07-20 09:21:53 -07:00
private typealias Data = (cachedObject: T?, lastUpdated: Date?)
private let content: Atomic<Data> = .init((nil, nil))
2021-08-23 11:20:55 -07:00
var lastUpdatedAt: Date? {
return self.content.value.lastUpdated
2021-07-20 09:21:53 -07:00
}
2021-07-30 14:27:36 -07:00
func isCacheStale(durationInSeconds: Double) -> Bool {
return self.content.withValue {
guard let lastUpdated = $0.lastUpdated else {
2021-07-20 09:21:53 -07:00
return true
}
let timeSinceLastCheck = -1.0 * lastUpdated.timeIntervalSinceNow
return timeSinceLastCheck >= durationInSeconds
}
}
2021-07-30 14:27:36 -07:00
func clearCacheTimestamp() {
self.content.modify { $0.lastUpdated = nil }
2021-07-20 09:21:53 -07:00
}
2021-07-30 14:27:36 -07:00
func clearCache() {
self.content.modify {
$0.cachedObject = nil
$0.lastUpdated = nil
2021-07-20 09:21:53 -07:00
}
}
2021-07-30 14:27:36 -07:00
func updateCacheTimestamp(date: Date) {
self.content.modify {
$0.lastUpdated = date
2021-07-20 09:21:53 -07:00
}
}
2021-07-30 14:27:36 -07:00
func cache(instance: T) {
self.content.modify {
$0.lastUpdated = Date()
$0.cachedObject = instance
2021-07-20 09:21:53 -07:00
}
}
2023-03-21 06:33:48 -07:00
var cachedInstance: T? {
return self.content.value.cachedObject
2021-07-20 09:21:53 -07:00
}
2021-07-30 14:27:36 -07:00
}
2022-08-31 13:30:38 -07:00
// @unchecked because:
// - Class is not `final` (it's mocked). This implicitly makes subclasses `Sendable` even if they're not thread-safe.
extension InMemoryCachedObject: @unchecked Sendable {}