Singleton with parameter in Kotlin

后端 未结 11 1136
无人及你
无人及你 2020-11-30 21:51

I am trying to convert an Android app from Java to Kotlin. There are a few singletons in the app. I used a companion object for the singletons without constructor parameters

11条回答
  •  庸人自扰
    2020-11-30 22:14

    I saw all the answers. I know this is a repeated answer but if we use the synchronized keyword on the method declaration, it will synchronize the whole method to the object or class. And synchronized block is not deprecated yet.

    You can use the following utility class to get the singleton behavior.

    open class SingletonWithContextCreator(val creator: (Context) -> T) {
        @Volatile
        private var instance: T? = null
    
        fun with(context: Context): T = instance ?: synchronized(this) {
            instance ?: creator(context).apply { instance = this }
        }
    }
    

    You can extend the above-mentioned class whichever class you wanted to make singleton.

    In your case the following is the code to make TasksLocalDataSource class singleton.

    companion object : SingletonWithContextCreator(::TasksLocalDataSource)
    

提交回复
热议问题