Last active
August 1, 2020 08:08
-
-
Save gaplo917/f186d5c541fbc0d6f77f9b720ec4694c to your computer and use it in GitHub Desktop.
Android Singleton Kotlin
This file contains 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 | |
@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) | |
} | |
} | |
} | |
} |
Shouldn't
if(initialized.getAndSet(true))
be negated?
Agree
shouldn't instance
be private?
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
Shouldn't
be negated?