Singleton Objects in Kotlin


What is a singleton property?

In the Android app, we use the singleton pattern for an object that needs to be created only once and used everywhere. The singleton pattern is a software design pattern that limits the installation of the class to "one" example only.

The Singleton class in Kotlin is also known as the Singleton object in Kotlin. The singleton class is a class that is defined in such a way that it can create only one example of the class and be used everywhere. We often make two different objects in the same class, but we must remember that to create two other entities, two other memories must be allowed for the objects.

Features of the Singleton Class

  1. One instance only - The Singleton class has only one example, and this is done by giving an example of the class within the class.
  2. Globally accessible – An example of a singleton class should be globally accessible so that each lesson can use it.
  3. Constructors are not allowed - We can use the init method to initialize our member variables.

The Rules for making a singleton class

  1. A private constructor
  2. A static reference of its class
  3. A static method
  4. Globally accessible object reference
  5. Stability across multiple threads

Singleton class with Arguments

In Android, we know that blocking a singleton's init on Android usually requires a contextual example. This can be done with Early Initiation and Lacy Initiation. In an earlier launch, all the components are launched in Application.onCreate () using the init () functions. But this slows down the application startup by blocking the main thread. Therefore, it is generally advisable to use the lazy initialization method. In lazy initialization, we use the context as an argument to a function that exemplifies singleton. We can achieve this with the singleton holder class. Also, to make it thread-secure, we need a way to sync and double-check locking.