-
-
Save Mr4Mike4/653784c64ab57b5a0a4cb7ae9504a3b1 to your computer and use it in GitHub Desktop.
Android Singleton Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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