How to make singleton for UserSettings?
Closed this issue · 1 comments
mezhevikin commented
Hi. Thank you for the library.
I have a question.
How to make singleton for UserSettings?
I'd like to set context in one place and then use UserSettings.shared
.
App.kt
UserSettings.init(applicationContext)
MainActivity.kt
UserSettings.shared.property = 2
zsmb13 commented
My suggestion would be to create that singleton instance using a dependency injection solution, such as Dagger 2 or Koin.
Otherwise, you can use an object
as your Krate
, with something like this:
object UserSettings : Krate {
override lateinit var sharedPreferences: SharedPreferences
fun init(context: Context) {
check(!::sharedPreferences.isInitialized)
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
}
var property by stringPref("property")
}
But be aware that this is fairly error-prone, as you'll get exceptions if you use the instance before initializing it. This here is just one implementation of a singleton pattern that takes a parameter in Kotlin, based on your suggested API, you can find more here.