Skip to content

Instantly share code, notes, and snippets.

@PetkevichPavel
Last active May 4, 2020 18:58
Show Gist options
  • Save PetkevichPavel/eb2e5bbf111414141da09dcb7b10f8ff to your computer and use it in GitHub Desktop.
Save PetkevichPavel/eb2e5bbf111414141da09dcb7b10f8ff to your computer and use it in GitHub Desktop.
SharedPreferences under Delegated properties
//SomeManager.kt
interface SomeManager {
var userId: Long?
var userName: String?
/**
* Returns true if user valid.
*/
fun isUserValid(): Boolean
/**
* Logout action clear all users data.
*/
fun clear()
}
//SomeManagerImpl.kt
class SomeManagerImpl(context: Context) : SharedPreferencesProvider, RegistrationManager {
private val cacheCleaners = mutableListOf<(() -> Unit)>()
private val masterKeyAlias = MasterKeys.getOrCreate(MasterKeys.AES256_GCM_SPEC)
override val preferences: SharedPreferences = EncryptedSharedPreferences.create(
getPrefName("userCreds"), masterKeyAlias, context,
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)
//The by keyword indicates that the property is controlled by the provided delegate instead of its own field.
override var userId: Long? by PreferencesDelegate<Long?>(::userId.name).addCacheCleaners(cacheCleaners)
override var userName: String? by PreferencesDelegate<String?>(::userName.name).addCacheCleaners(cacheCleaners)
override fun isUserValid(): Boolean = userId != null
override fun clear() {
cacheCleaners.forEach { it.invoke() }
preferences.run { edit().clear().commit() }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment