Skip to content

Instantly share code, notes, and snippets.

@polson
Last active September 9, 2019 21:10
Show Gist options
  • Save polson/f2e362f2949d4cdff7e6a4b08f34e29a to your computer and use it in GitHub Desktop.
Save polson/f2e362f2949d4cdff7e6a4b08f34e29a to your computer and use it in GitHub Desktop.
/**
* Provides a single instance of a class requiring a context. Can be inherited by a companion
* object to easily make it a singleton
*/
abstract class SingletonWithContext<T> {
@Volatile
private var instance: T? = null
fun getInstance(context: Context): T =
instance ?: synchronized(this) {
instance ?: buildInstance(context).also { instance = it }
}
protected abstract fun buildInstance(context: Context): T
}
/**
* A singleton that uses Shared Preferences on Android
*/
class PrefsHelper private constructor(val sharedPreferences: SharedPreferences) {
companion object : SingletonWithContext<PrefsHelper>() {
override fun buildInstance(context: Context): PrefsHelper {
val sharedPreferences = context.applicationContext.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE)
return PrefsHelper(sharedPreferences)
}
}
}
/**
* Example usage of our singleton
*/
class ExampleActivity : FragmentActivity() {
val prefsHelper by lazy { PrefsHelper.getInstance(this) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment