Home > front end >  Create Singleton classes in Kotlin
Create Singleton classes in Kotlin

Time:10-30

I want to create singleton classes in kotlin which can be released in future.

Here is the code.

companion object {
        // Singleton prevents multiple instances of repository opening at the
        // same time.
        @Volatile
        private var INSTANCE: AudioRepo? = null

        @Volatile
        private var counter: Int = 0

        @JvmStatic
        fun release() {
            synchronized(this) {
                // if counter is already 0 some sort of error has occurred
                if (counter == 0)
                    throw IllegalStateException("Counter variable is 0")
                counter--
                if (counter == 0) {
                    INSTANCE!!.destroy()
                    INSTANCE = null
                }
            }
        }

        @JvmStatic
        fun get(context: Context): AudioRepo {
            // if the INSTANCE is not null, then return it,
            synchronized(this) {
                counter  
                return INSTANCE ?: run {
                    val instance = AudioRepo(context.applicationContext as Application)
                    INSTANCE = instance
                    instance
                }
            }
        }
    }

Please check if this is good or I am doing something wronge.

The idea here is if an instance is obtaintained using get it needs to be released with release(). The counter determines when to clear the object.

Update Since most of people seem to be confused why I need such approach. Let me explain.

The class AudioRepo needs to be Singleton in UI and Service. Since I cant use any scope with hilt(I guess) to make it singleton so I used this approach.

I cant use kotlin object classs single I need to release the Couroutine Scope housed by audio repo and unregister Content Observer.

I can't use auto closable (as far as I Understand it) becuase I Use the instance in child composable of Jet Pack compose and In Service.

CodePudding user response:

object is a special keyword for singletons in Kotlin. You can just type something as simple as this to get working singleton class:

object MySingleton

or when you want some member functions:

object MySingleton {
    fun someFunction(...) {...}
}

And then use it:

MySingleton.someFunction(...)

there is a reference: https://kotlinlang.org/docs/reference/object-declarations.html#object-declarations

CodePudding user response:

I think you should consider my solution:

open class Singleton<out T : Any>(creator: () -> T) {
    private var creator: (() -> T)? = creator
    @Volatile
    private var instance: T? = null
    fun getInstance(): T {
        val i = instance
        if (i != null)
            return i
        return synchronized(this) {
            val i2 = instance
            if (i2 != null)
                i2
            else {
                val created = creator!!()
                instance = created
                creator = null
                created
            }
        }
    }
}

--- Example

class ImageLoader private constructor(){
    companion object : Singleton<ImageLoader>(::ImageLoader)
}
  • Related