Pankaj Rai 🇮🇳
1 min readOct 14, 2020

--

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()

}

--

--

Pankaj Rai 🇮🇳
Pankaj Rai 🇮🇳

Written by Pankaj Rai 🇮🇳

Software Engineer | GDE Android & Firebase | YouTuber — All Techies

Responses (1)