When building modern Android applications, loading images seems deceptively simple until you encounter edge cases: OutOfMemory (OOM) crashes during fast scrolling in lists, redundant network fetches for identical image URLs, corrupted disk caches after unexpected process termination, rotated JPEG photos from phone cameras, and layout jank during Jetpack Compose recomposition.
While mature libraries like Glide and Coil exist, understanding the underlying mechanics of an image loading pipeline—and engineering a clean, modular SDK adhering to Clean Architecture—is essential for building resilient, high-performance Android apps.
In this deep dive, we break down the design, architecture, and internals of KotlinImageLoader 1.1.0: an open-source Android image loading SDK built from scratch in 100% Kotlin with Coroutines, StateFlow, and Jetpack Compose.
Architecture & Module Decomposition
To prevent monolithic bloat, guarantee strict layer boundaries, and optimize build times for consuming applications, KotlinImageLoader is architected across 7 focused Gradle modules:
image-compose, image-view ──► image-loader, image-core
image-loader ──► image-data, image-domain, image-core
image-data ──► image-domain, image-core
image-mvi ──► image-domain, image-core
image-domain ──► image-core
-
image-core: Defines core models (ImageRequest,ImageSize,ImageResult), the transformation interface and built-in transformations, and network monitoring. It uses Android APIs such asBitmap. -
image-domain: HousesLoadImageUseCase, request validation, and theImageRepositorycontract. -
image-data: Encapsulates data sources: thread-safe memory LRU cache, disk LRU cache with temp-file-and-rename writes, HTTP network fetcher, repository-level retry with increasing delay, and format decoders (GIF, WebP, SVG, JPEG/PNG). -
image-loader: The main client-facing API (ImageLoader,RealImageLoader,SingletonImageLoader) that wires together the use case, repository, caches and coroutine dispatchers. -
image-compose: Jetpack Compose UI components (AsyncImage,ZoomableAsyncImage) featuring state management, crossfade animations, and smooth touch gestures. -
image-view: Classic Android View integration (ImageView.loadImage(),ZoomableImageView) with automatic item recycling cancellation in RecyclerViews. -
image-mvi: Unidirectional data-flow (MVI) state container exposingStateFlow<ImageState>for advanced custom UI rendering pipelines.
Core Engine Internals
1. Two-Tier Caching
Request ──► [Memory LRU Cache] ──(Hit)──► Render Bitmap
│ (Miss)
▼
[Disk LRU Cache] ───(Hit)────► Decode ──► Populate Memory ──► Render
│ (Miss)
▼
[Network Fetcher] ──(HTTP 200)──────► Disk Write (temp + rename) ──► Decode ──► Render
-
Memory Cache: A synchronized, access-ordered
LinkedHashMap, sized by default to 25% of the maximum JVM heap (Runtime.maxMemory()). Bitmap sizes are measured withbitmap.byteCount. -
Disk Cache: After a download completes, the repository passes the image bytes to the disk cache, which writes them to a temporary file and then renames it to the final key (an MD5 hash of the request data). A process killed mid-write does not leave a partial file under that key. This is not a journaled cache. Version 1.1.0 has no startup cleanup for leftover temp files, and it does not
fsyncbefore renaming, so it makes no durability guarantee across power loss.
2. Request Deduplication
When rendering a feed containing duplicate author avatars, firing redundant HTTP requests degrades bandwidth and battery life.
The suspend load path (execute()) uses a Mutex-guarded map of in-flight Deferred results:
- The first request starts the fetch and decode, and registers its
Deferred. - Concurrent requests with the same data and target size join it instead of making a new network call.
- When it completes, waiting callers receive the result and the entry is removed.
Current limitations: the key does not include transformations, so concurrent requests that differ only in transformations can receive the same result. The shared work also belongs to the first caller's coroutine scope, so cancelling that caller can cancel it for the others. The flow() path used by AsyncImage and ImageView.loadImage() does not use this deduplication.
3. Cooperative Lifecycle Cancellation
Image requests in fast-scrolling lists must abort immediately when an item leaves the viewport:
-
Jetpack Compose:
AsyncImagecollects the request flow inside aLaunchedEffectkeyed on the resolved request, the loader and network state. Leaving the composition cancels that coroutine. -
Android Views / RecyclerView:
ImageView.loadImage()stores aDisposablein a view tag. Binding a new request to the same view, or detaching the view, disposes the previous one. A request ID check stops stale results from being applied.
4. Automatic EXIF Orientation (1–8)
Smartphone camera sensors frequently write photos rotated 90° or 270°, embedding EXIF orientation metadata tags (1 through 8) in the JPEG APP1 segment (0xFFE1).
KotlinImageLoader has an ExifOrientationHandler in image-data, with its own Kotlin parser and a fallback to Android's ExifInterface:
- It reads the orientation tag from the encoded JPEG bytes.
- Orientation 1 (Normal): No new bitmap is created; the decoded bitmap is returned as is.
-
Orientations 2–8: A
Matrixtransform (rotation and/or flip) is applied after downsampled decoding and before user transformations. - Cached raw image bytes on disk remain intact and unaltered.
🖼 Modular Image Formats & API Limitations
KotlinImageLoader supports modern and legacy image formats with graceful platform degradation:
| Format | Decoding Mechanism | Supported Android APIs | Runtime Behavior & Graceful Degradation |
|---|---|---|---|
| JPEG / PNG |
BitmapFactory with inSampleSize downsampling |
API 26+ | Standard hardware-accelerated bitmap decoding |
| Static WebP |
BitmapFactory with WebP headers |
API 26+ | Native decoding on all supported Android versions |
| Animated GIF |
ImageDecoder / BitmapFactory fallback |
API 26+ | Static 1st frame on API 26–27; animated drawable on API 28+ (Views) |
| Animated WebP |
ImageDecoder / BitmapFactory fallback |
API 26+ | Static 1st frame on API 26–27; animated drawable on API 28+ (Views) |
| SVG Vectors | AndroidX PathParser + Canvas renderer |
API 26+ | XML parsing and custom vector canvas rendering |
AsyncImagecurrently draws animated drawables into a bitmap, so they do not animate in Compose.
Benchmark Harness
The repository includes a JVM benchmark test (ImageLoaderBenchmarkTest) covering memory hits, disk hits (30 iterations each), cold loads (10 iterations) and 10 concurrent requests. It uses a mock fetcher with a simulated 12 ms delay and a mock decoder with a simulated 4 ms delay.
Note: Its timings do not measure real image decoding, network latency or on-device performance.
Quick Start & Installation
1. Repository Configuration
Add the JitPack repository to your root settings.gradle.kts:
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven { url = uri("https://jitpack.io") }
}
}
2. Add Dependencies
Add the required modular artifacts to your module build.gradle.kts:
dependencies {
// Core image loader engine
implementation("com.github.gargpadmakar.KotlinImageLoader:image-loader:1.1.0")
// Jetpack Compose components (AsyncImage, ZoomableAsyncImage)
implementation("com.github.gargpadmakar.KotlinImageLoader:image-compose:1.1.0")
// Android View extensions (ImageView.loadImage, ZoomableImageView)
implementation("com.github.gargpadmakar.KotlinImageLoader:image-view:1.1.0")
// Optional: Unidirectional MVI state management
implementation("com.github.gargpadmakar.KotlinImageLoader:image-mvi:1.1.0")
}
3. Usage Examples
Jetpack Compose AsyncImage
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.padmakar.imageloader.compose.AsyncImage
import com.padmakar.imageloader.core.model.ImageRequest
import com.padmakar.imageloader.core.transform.RoundedCornersTransformation
@Composable
fun UserAvatar(imageUrl: String) {
AsyncImage(
model = ImageRequest.Builder(imageUrl)
.crossfade(true)
.transform(RoundedCornersTransformation(radiusPixels = 16f))
.build(),
contentDescription = "User Avatar",
modifier = Modifier.size(96.dp)
)
}
Jetpack Compose ZoomableAsyncImage
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.padmakar.imageloader.compose.ZoomableAsyncImage
@Composable
fun PhotoViewer(imageUrl: String) {
ZoomableAsyncImage(
model = imageUrl,
contentDescription = "Zoomable High-Res Photo",
modifier = Modifier.fillMaxSize(),
maxScale = 4.0f
)
}
Android View ImageView.loadImage()
import com.padmakar.imageloader.view.loadImage
import com.padmakar.imageloader.core.transform.CircleCropTransformation
imageView.loadImage("https://images.unsplash.com/photo-1534528741775-53994a69daeb") {
placeholder(R.drawable.ic_placeholder)
error(R.drawable.ic_error)
crossfade(true)
transform(CircleCropTransformation())
}
About the Author
Padmakar Garg is an Android Developer with 8+ years of experience in Kotlin, Java, Jetpack Compose, KMP, scalable architecture, mobile security, and high-performance app development.
- GitHub: github.com/gargpadmakar
- Project Repository: KotlinImageLoader on GitHub
- Release Tag: v1.1.0 on JitPack
- License: Apache 2.0
Top comments (5)
The corrupted disk cache after process termination is the edge case I'd look at first in the data module, since a half written file from a killed process can look like a valid entry on the next read. Writing to a temp file and renaming once it completes is the usual guard, roughly what DiskLruCache does with its journal. Which approach did you take there?
Thanks, Prikshit. I went with temp file and rename. Once the download completes, the bytes are written to a temp file, which is renamed to the final key only after the write finishes. So if the process is killed mid-write, the partial file never appears under the key that get() reads.
Unlike DiskLruCache, there's no journal, even though my article said there was, so that needs correcting. Version 1.1.0 also has no startup cleanup, so a leftover temp file can stay on disk and count toward the cache size until it's evicted or the cache is cleared. And since I don't fsync before the rename, I wouldn't claim durability through power loss.
Temp file and rename is the right call, and it's good that you're upfront about the missing fsync. For the leftover files, a small sweep at startup that deletes anything with your temp suffix before the cache size gets computed would close that gap cheaply. Right now those orphans count against the limit, so a few crashes during big downloads could evict good entries early.
The request-deduplication registry is the detail I'd steal first — one Deferred per URL in a ConcurrentHashMap, so a feed full of the same avatar only pays for one network fetch and every waiter gets the result at once. That is the kind of bug that only shows up in a real scrolling list, not in a demo.
The atomic disk cache is the other one that tells me this was built from real pain: write to a .tmp file and rename it on completion, so a killed process can never leave a half-written file pretending to be a valid image. And checking EXIF orientation from the JPEG byte stream without decoding the whole bitmap first is a nice touch — most hand-rolled loaders decode first and pay for it twice.
One thing I am curious about: the dedup key is the URL, but what happens when the same URL is requested at two different sizes or with two different transformations — do they share the one in-flight Deferred and transform separately afterwards, or does the key include the transformation? And have you measured the 25%-of-heap memory cache sizing on a low-end device yet, or is that still on the list to try on real hardware?
Thanks Abdullah, great questions. I went back to the code, and the first one exposed real bugs.
The dedup key is data + size and leaves out transformations (the memory cache key includes them). So two concurrent requests for the same URL and size with different transformations can share one Deferred, and the second caller gets the first caller's transformed bitmap. Different sizes get separate keys, so they don't share the fetch.
Also, dedup is only wired into loadImage(). AsyncImage and ImageView.loadImage() go through streamImage(), which skips it, so the repeated-avatar benefit doesn't currently apply to those UI paths. And since the shared work is a child of the first caller, cancelling that caller also cancels the waiters.
My plan is to deduplicate only the raw byte fetch (keyed on URL + headers), run it in a loader-owned scope with proper handling for when all callers cancel, decode and transform per caller, and use it in the streaming path too.
On the 25% sizing: I haven't tested it on a low-end device yet. It's 25% of the app's max heap (Runtime.maxMemory()), and my published benchmarks are from a JVM test harness, so it still needs validation on real hardware.