In Android development, caching is a critical technique for storing data locally for quicker access, reducing network calls, and enhancing the user experience. One popular caching technique is the Least Recently Used (LRU) cache, which automatically evicts the least recently accessed data when the cache reaches its limit. This post explores how to implement an LRU cache in Android using Kotlin and Jetpack Compose.
What is an LRU Cache?
Least Recently Used (LRU) is a caching strategy that removes the least recently accessed items first when the cache exceeds its defined limit. It's optimal when you want to cache a limited amount of data, such as images, objects, or API responses, and ensure only frequently used items remain in memory.
Benefits:
-
Reduces memory footprint
-
Speeds up data retrieval
-
Avoids unnecessary API calls or file reads
-
Automatically manages cache eviction
Use Cases of LRU Cache in Android
Use Case | Description |
---|---|
Image Caching | Store bitmap images fetched from the network to avoid repeated downloads |
Network Responses | Save HTTP responses (e.g., user profile, dashboard data) to speed up load times |
File or Object Caching | Cache local files or data models in memory for quick reuse |
Custom In-App Caching | Temporary store for autocomplete suggestions, search history, etc. |
Implementing LRU Cache in Kotlin (Without External Libraries)
Step 1: Create an LRU Cache Manager
class LruCacheManager<K, V>(maxSize: Int) {
private val cache = object : LruCache<K, V>(maxSize) {
override fun sizeOf(key: K, value: V): Int {
return 1 // Customize this if needed (e.g., for Bitmaps)
}
}
fun put(key: K, value: V) {
cache.put(key, value)
}
fun get(key: K): V? {
return cache.get(key)
}
fun evictAll() {
cache.evictAll()
}
}
☝️ Note: This uses Android’s built-in
LruCache<K, V>
fromandroid.util.LruCache
.
Example: Caching User Profiles
Let’s say you’re loading user profiles from an API, and want to cache them in memory to avoid reloading them repeatedly.
Step 2: Define a simple data model
data class UserProfile(val id: Int, val name: String, val avatarUrl: String)
Step 3: Create a ViewModel using StateFlow and LruCache
class UserProfileViewModel : ViewModel() {
private val cache = LruCacheManager<Int, UserProfile>(maxSize = 5)
private val _userProfile = MutableStateFlow<UserProfile?>(null)
val userProfile: StateFlow<UserProfile?> = _userProfile
fun loadUserProfile(userId: Int) {
cache.get(userId)?.let {
_userProfile.value = it
return
}
viewModelScope.launch {
// Simulate network call
delay(1000)
val user = UserProfile(userId, "User $userId", "https://picsum.photos/200/200?random=$userId")
cache.put(userId, user)
_userProfile.value = user
}
}
}
Jetpack Compose UI
@Composable
fun UserProfileScreen(viewModel: UserProfileViewModel = viewModel()) {
val profile by viewModel.userProfile.collectAsState()
Column(
modifier = Modifier.fillMaxSize().padding(16.dp),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Button(onClick = { viewModel.loadUserProfile((1..10).random()) }) {
Text("Load Random User")
}
Spacer(modifier = Modifier.height(20.dp))
profile?.let {
Text(text = it.name, style = MaterialTheme.typography.titleLarge)
AsyncImage(
model = it.avatarUrl,
contentDescription = "Avatar",
modifier = Modifier.size(120.dp).clip(CircleShape)
)
} ?: Text("No user loaded")
}
}
Best Practices for Using LRU Cache
Tip | Description |
---|---|
Use LruCache only for in-memory caching |
Do not use it for persistent or disk-based caching |
Define a sensible maxSize |
Based on app usage pattern and available memory |
For image caching, use Bitmap size as the unit |
Override sizeOf() method |
Evict cache on memory warnings | Use onTrimMemory() or onLowMemory() callbacks |
Use libraries like Coil, Glide, or Picasso | They offer built-in LRU support for image loading |
๐ Remember
The LRU caching mechanism is a simple yet powerful technique in Android development. It keeps your UI snappy and responsive by reducing network usage and data load time. While libraries like Glide manage LRU for images out of the box, creating your custom LRU cache gives you flexibility and control—especially when caching JSON responses or domain objects.
Pro Tip: Combine
LruCache
withStateFlow
andJetpack Compose
for real-time UI updates and smoother UX.
#AndroidDevelopment #Kotlin #JetpackCompose #LRUCache #CachingInAndroid #StateFlow #PerformanceOptimization
๐ข Feedback: Did you find this article helpful? Let me know your thoughts or suggestions for improvements! ๐ please leave a comment below. I’d love to hear from you! ๐
Happy coding! ๐ป✨
0 comments:
Post a Comment