Parcourir la source

Add `keepWhenEnteringBackground` to memory cache

onevcat il y a 4 ans
Parent
commit
95393a0544
1 fichiers modifiés avec 18 ajouts et 2 suppressions
  1. 18 2
      Sources/Cache/MemoryStorage.swift

+ 18 - 2
Sources/Cache/MemoryStorage.swift

@@ -126,7 +126,12 @@ public enum MemoryStorage {
             // The expiration indicates that already expired, no need to store.
             // The expiration indicates that already expired, no need to store.
             guard !expiration.isExpired else { return }
             guard !expiration.isExpired else { return }
             
             
-            let object = BackgroundKeepingStorageObject(value, key: key, expiration: expiration)
+            let object: StorageObject<T>
+            if config.keepWhenEnteringBackground {
+                object = BackgroundKeepingStorageObject(value, key: key, expiration: expiration)
+            } else {
+                object = StorageObject(value, key: key, expiration: expiration)
+            }
             storage.setObject(object, forKey: key as NSString, cost: value.cacheCost)
             storage.setObject(object, forKey: key as NSString, cost: value.cacheCost)
             keys.insert(key)
             keys.insert(key)
         }
         }
@@ -192,7 +197,18 @@ extension MemoryStorage {
         public var expiration: StorageExpiration = .seconds(300)
         public var expiration: StorageExpiration = .seconds(300)
 
 
         /// The time interval between the storage do clean work for swiping expired items.
         /// The time interval between the storage do clean work for swiping expired items.
-        public let cleanInterval: TimeInterval
+        public var cleanInterval: TimeInterval
+        
+        /// Whether the newly added items to memory cache should be purged when the app goes to background.
+        ///
+        /// By default, the cached items in memory will be purged as soon as the app goes to background to ensure
+        /// least memory footprint. Enabling this would prevent this behavior and keep the items alive in cache even
+        /// when your app is not in foreground anymore.
+        ///
+        /// Default is `false`. After setting `true`, only the newly added cache objects are affected. Existing
+        /// objects which are already in the cache while this value was `false` will be still be purged when entering
+        /// background.
+        public var keepWhenEnteringBackground: Bool = false
 
 
         /// Creates a config from a given `totalCostLimit` value.
         /// Creates a config from a given `totalCostLimit` value.
         ///
         ///