Skip to content

Instantly share code, notes, and snippets.

@Mr4Mike4
Forked from gaplo917/TasksLocalDataSource.kt
Created February 12, 2017 10:44
Show Gist options
  • Save Mr4Mike4/653784c64ab57b5a0a4cb7ae9504a3b1 to your computer and use it in GitHub Desktop.
Save Mr4Mike4/653784c64ab57b5a0a4cb7ae9504a3b1 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
private lateinit var INSTANCE: TasksLocalDataSource
private val initialized = AtomicBoolean()
// 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)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment