Kotlin version of Java's getInstance()


#1

So recently I’ve been using Android Architecture Components. In some example inside ViewModel we need to have a singleton of LiveData object (locationData). What is the proper way to do this in Kotlin. I also need to pass context to this this singleton.

class LocationViewModel extends ViewModel {
    private LiveData<Location> locationData = null;
 
    LiveData<Location> getLocation(Context context) {
        if (locationData == null) {
            locationData = new MyLocationListener(context);
        }
        return locationData;
    }
}

That’s my dummy implementation:

class LocationViewModel: ViewModel() {
    lateinit var locationData: MyLocationListener

    fun getLocation(context: Context): MyLocationListener {
        locationData = MyLocationListener(context)
        return locationData
    }

#2

I would do it like this:

  class LocationViewModel: ViewModel(){
    var locationData: MyLocationListener? = null
        fun getLocation(context: Context) = locationData ? : synchronized(this) {
           MyLocationListener(context).also{
                locationData = it
            }
       }
} 

. I found this implementation online https://medium.com/@BladeCoder/kotlin-singletons-with-argument-194ef06edd9e