Having a singleton should do the trick here, something like this
object LocalStorage {
val dataStore = StorageSampleApp.appContext.createDataStore(name = "sample")
suspend inline fun <reified T> storeValue(key: Preferences.Key<T>, value: Any) {
dataStore.edit {
it[key] = value as T
}
}
suspend inline fun <reified T> readValue(
key: Preferences.Key<T>,
crossinline responseFunc: T.() -> Unit
) {
dataStore.getFromLocalStorage(key) {
responseFunc.invoke(this)
}
}
}
//Now to read and write you can call following function from any activity or fragment
//Write
LocalStorage.storeValue(PreferenceKeys.USER_ID, mUserId)
//Read
LocalStorage.readValue(PreferenceKeys.USER_ID) {
tvUserId.text = this.toString()
}