Skip to content

Instantly share code, notes, and snippets.

@gaplo917
Last active August 1, 2020 08:08
Show Gist options
  • Save gaplo917/f186d5c541fbc0d6f77f9b720ec4694c to your computer and use it in GitHub Desktop.
Save gaplo917/f186d5c541fbc0d6f77f9b720ec4694c to your computer and use it in GitHub Desktop.
Android Singleton Kotlin
//http://stackoverflow.com/questions/40398072/singleton-with-parameter-in-kotlin
class TasksLocalDataSource private constructor(context: Context) : TasksDataSource {
private val mDbHelper: TasksDbHelper
init {
// You cannot pass null in kotlin unless you are using `context: Context?`
// therefore, checking null is useless
// checkNotNull(context)
mDbHelper = TasksDbHelper(context)
}
companion object {
// do not expose var, it includes getter/setting and makes confusion to other users
@Volatile
private lateinit var INSTANCE: TasksLocalDataSource
private val initialized = AtomicBoolean(false)
// Use `val` and define the getter only
// kotlin will throw `kotlin.UninitializedPropertyAccessException` if the INSTANCE is not initialized
val instance: TasksLocalDataSource get() = INSTANCE
// Call it in Application.onCreate() is enough
fun initialize(context: Context) {
if(!initialized.getAndSet(true)) {
INSTANCE = TasksLocalDataSource(context)
}
}
}
}
@gaplo917
Copy link
Author

gaplo917 commented Aug 1, 2020

shouldn't instance be private?

The instance in val instance: TasksLocalDataSource get() = INSTANCE is a getter function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment