Android: Create Your Own Image Loading Library in Kotlin #DIY

Mahes Sivakumar
3 min readMar 17, 2019

This post is for android beginners to understand the working of Image loading library by writing our own.

Nowadays, loading a remote image into an ImageView is a common need in android app development. Whenever we need to do it, we add libraries like Picasso/Glide/Fresco to your app.

Have you ever tried to write your own Image Loading Library? If not, we will try to create our own Image Loading Library in this post.

If we look into it on an abstract level, it looks like these libraries are downloading the given URL and update the UI once the image gets downloaded. But, it does more things like caching, managing background task, downscaling, handling OOM Exceptions, handling duplicate request…

Before start coding, lets breakdown and list out ImageLoader flow,

  1. ImageLoader receives a request which contains an ImageView and Image URL
  2. Check whether Image exist in cache or not
  3. If Image exists in the cache, then scale the Image to the required size and load it onto ImageView.
  4. If Image doesn't exist in the cache, then Download the Image, write it to the cache and execute Step 3

Required Components :

For Caching: There are two choices available for caching. One is Memory cache and another one is Disk Cache.

In Memory cache, data is stored in the application memory and have faster read rate but data will get cleared once the application got killed. In Disk cache, data is stored and persisted in the disk but it has slower read time compared to the Memory cache.

In our example, we will use Memory cache (LruCache)

For Background Execution: ImageLoader will receive multiple image load request. At that time, it needs to have a thread pool to handle multiple image download.

In our example, we use ExecutorService for handling background task.

For Handling Duplicate Request: Sometimes, an ImageView may make more than one request[ E.g. ImageView in a RecyclerView]. Downloading Image or loading Image from the cache for every request is unnecessary.

To avoid that, ImageLoader will store all the request details which will be used to find out whether any duplicate request is made or not. To save request detail, we will use WeakHashMap<ImageView, String[ImageUrl]>

Work Flow:

Check out the code here :

What more can be done:

  1. Replace LruCache with Disk Cache.
  2. Change thread pool size based on network type or speed.
  3. GIF Support

The written Image Loader is not a perfect one and not an alternative to other libraries. But by writing, we have got an idea about how it works.

Some days you just have to create your own sunshine.

Thanks for reading! ❤️. Please let me know what you think about this.

Image Courtesy: Photo by rawpixel.com from Pexels

--

--

Mahes Sivakumar

{ Mahes | மகேஷ் } Coding Clown, Geek, Cyclist, Blogger, Foodie, Aspiring Keyboard Player, Green Robot Engineer, React Developer. AppyBot.in