What is “Lazy Loading” in Android-Kotlin?

Ipek
3 min readOct 2, 2023

--

Hello everyone. In this story, I will try to explain how to use the “lazy loading” feature commonly used in programming in Android development and in which situations you can use it. While preparing this article, I tried to convey the questions that came to my mind as if I were thinking out loud and to add the examples I found without deviating from the topic.

Lazy loading means loading or creating certain data or content of an application only when needed. This allows the application to load them at the moment the user requests, instead of loading all data or content initially. We can implement such a process more easily using the “lazy” keyword, a feature of Kotlin.

After the definition, let’s take a look at the difference between “lateinit” and “lazy” keywords, which is the first question that came to my mind.

Firstly, both keywords are important initialization properties, meaning they are used to set the initial values of variables. However, there are some important differences between them.

lateinit:

  • lateinit can only be used with var type variables.
  • By using this keyword, you indicate that you can assign the initial value of a variable later.
  • If you try to access a variable defined with lateinit before its initial value is assigned, you will get a runtime error.

lazy:

  • lazy is used with val type variables.
  • By using this keyword, you lazily initialize a variable, meaning the initial value of the variable is calculated only at the first access and not recalculated during subsequent accesses.
  • The variable is not accessed until the initial value is calculated.

Now, to better understand how and where we can use these keywords, let’s move on to scenario examples:

1- Data Retrieval Operations As another example, we can consider data retrieval operations. For instance, using the lazy keyword with Kotlin when using Retrofit, an API service can be written like this:

class ApiService {

companion object {
private const val BASE_URL = "https://api.example.com/"

// We created the Retrofit object using lazy loading
private val retrofit: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}

val apiService: ApiService by lazy {
retrofit.create(ApiService::class.java)
}
}
}

In the above example, we create a Retrofit object and a service object using Retrofit and Kotlin’s by lazy feature. These are not created immediately when the application starts but rather when they are first needed. This way, unnecessary loading processes are avoided when the application starts, and data retrieval only occurs when necessary.

An immediate question here might be, “How can we do this in Java without using by lazy?” I tried to rewrite the previous Kotlin example in Java for cases where we cannot use the lazy keyword to implement lazy loading:

public class ApiService {

private static final String BASE_URL = "https://api.example.com/";

// We will use static variables and methods instead of a Companion object
private static Retrofit retrofit;

public static Retrofit getRetrofitInstance() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}

public static ApiService getApiService() {
return getRetrofitInstance().create(ApiService.class);
}
}

To lazily load Retrofit, we created a Retrofit instance with null checking and imitated the previous Kotlin example in Java.

2- Image Loading Consider an image gallery application, for example. Loading all images initially can lead to increased data usage. Lazy loading allows the user to load an image when they click on it or scroll to it. This way, the application starts faster, consumes fewer resources, and provides a better user experience.

3- List Views When using large list views (RecyclerView or ListView), lazy loading is used to load data only when a specific portion of the view needs it, instead of loading all the data at once. This helps the application start faster and consume less memory.

4- Content Download and Media Players Applications that provide video or music streaming can use lazy loading to download content before playing it. When a user wants to play a media file, that file is loaded.

5- Maps and Location Data Map-based applications can use lazy loading to load map data by focusing on areas where the user zooms in or navigates.

I hope this article has been as useful to everyone as it has been to me. If you think there are any mistakes or omissions, please do not hesitate to reach out!

--

--

Ipek
Ipek

Written by Ipek

Jr. Android Developer @Appcent, Software Engineering Student