2021-07-20 09:21:53 -07:00
|
|
|
//
|
2021-08-24 12:56:37 -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.
|
|
|
|
|
//
|
|
|
|
|
|
2021-08-26 13:54:50 -07:00
|
|
|
import Foundation
|
|
|
|
|
|
2021-08-24 12:56:37 -07:00
|
|
|
class InMemoryCachedObject<T> {
|
2021-07-20 09:21:53 -07:00
|
|
|
|
2021-11-29 10:12:56 -08: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? {
|
2021-11-29 10:12:56 -08:00
|
|
|
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 {
|
2021-11-29 10:12:56 -08:00
|
|
|
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() {
|
2021-11-29 10:12:56 -08:00
|
|
|
self.content.modify { $0.lastUpdated = nil }
|
2021-07-20 09:21:53 -07:00
|
|
|
}
|
|
|
|
|
|
2021-07-30 14:27:36 -07:00
|
|
|
func clearCache() {
|
2021-11-29 10:12:56 -08:00
|
|
|
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) {
|
2021-11-29 10:12:56 -08:00
|
|
|
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) {
|
2021-11-29 10:12:56 -08:00
|
|
|
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? {
|
2021-11-29 10:12:56 -08:00
|
|
|
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 {}
|