hybrid_lru_cache 0.0.1
hybrid_lru_cache: ^0.0.1 copied to clipboard
A hybrid LRU cache system within File
hybrid_lru_cache #
A generic, persistent, least-recently-used (LRU) cache for Flutter applications, leveraging an in-memory map for speed and a file for persistence.
Features #
- ⚡ Fast In-Memory Access: Uses a
Mapfor quick, O(1) average time complexity for gets and sets. - 💾 Persistent Storage: Automatically persists the cache to a file on disk, so data survives across app sessions.
- 🗑️ LRU Eviction Policy: Automatically removes the least recently used items when the cache reaches its configured size limit.
- ⌛ Time-To-Live (TTL): Set an optional duration for entries to automatically expire.
- 🧬 Fully Generic: Can store any type of object, provided you supply functions for encoding and decoding.
- 🔧 Configurable: Easily configure the maximum number of entries and the TTL.
Getting Started #
Add the package to your pubspec.yaml file:
dependencies:
hybrid_lru_cache: ^0.0.1
Then, run flutter pub get to install the package.
Usage #
The HybridLruCache is generic and requires encoder and decoder functions to handle persistence for custom objects.
Here's an example of how to cache a custom User object.
1. Define your data model #
Create a class for the data you want to cache. It's a good practice to include fromJson and toJson methods.
class User {
final String name;
final int age;
User({required this.name, required this.age});
// Factory constructor to create a User from a map
factory User.fromJson(Map<String, dynamic> json) {
return User(
name: json['name'] as String,
age: json['age'] as int,
);
}
// Method to convert a User instance to a map
Map<String, dynamic> toJson() {
return {
'name': name,
'age': age,
};
}
}
2. Create and use the cache #
Instantiate HybridLruCache and provide the required encoder and decoder functions.
import 'package:hybrid_lru_cache/hybrid_lru_cache.dart';
void main() async {
// Initialize the cache with a max of 50 entries and a 1-hour TTL.
final userCache = HybridLruCache<User>(
maxEntries: 50,
ttl: const Duration(hours: 1),
encoder: (user) => user.toJson(),
decoder: (json) => User.fromJson(json),
);
final user = User(name: 'John Doe', age: 30);
// Add an entry to the cache
print('Setting user...');
await userCache.set('user_123', user);
// Retrieve an entry from the cache
print('Getting user...');
final cachedUser = await userCache.get('user_123');
if (cachedUser != null) {
print('Found user in cache: ${cachedUser.name}');
}
// This will add 'user_456' and, if the cache is full,
// evict the least recently used entry.
await userCache.set('user_456', User(name: 'Jane Doe', age: 28));
// Clear the entire cache
print('Clearing cache...');
await userCache.clear();
final clearedUser = await userCache.get('user_123');
print('User after clear: ${clearedUser == null ? 'null' : 'exists'}');
}
API Reference #
HybridLruCache<T> #
The main class for the cache.
Constructor:
HybridLruCache({
this.maxEntries = 194,
this.ttl = const Duration(seconds: 60),
required this.encoder,
required this.decoder,
this.cacheFileName = "hybrid_lru_cache",
})
maxEntries: The maximum number of entries the cache can hold. When this limit is exceeded, the least recently used entry is removed.ttl: The Time-To-Live for each cache entry. Expired entries are removed upon access.encoder: A function that takes your object of typeTand converts it into aMap<String, dynamic>for JSON serialization.decoder: A function that takes aMap<String, dynamic>and decodes it back into an object of typeT.cacheFileName: An optional file name for the persistent cache file.
Methods:
Future<T?> get(String key): Retrieves an entry from the cache. If the entry exists and is not expired, it's returned and promoted to the most recently used position. Returnsnullif the key is not found or the entry is expired.Future<void> set(String key, T value): Adds or updates an entry in the cache. If the cache is full, the least recently used entry is evicted.Future<void> clear(): Removes all entries from the in-memory cache and deletes the persistent file from disk.
How It Works #
This cache combines an in-memory Map for fast read/write operations with a JSON file for persistence.
- When you
getorsetan item, the cache is first loaded from the file into the in-memory map if it's not already loaded. get(key)operations mark the entry as "most recently used."set(key, value)operations add the item as "most recently used." IfmaxEntriesis exceeded, the "least recently used" entry is dropped.- All mutations (
set,clear, or eviction due togeton an expired item) are persisted to the JSON file in the application's temporary directory.
This hybrid approach provides the performance benefits of an in-memory cache with the durability of on-disk storage.