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
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)