Skip to content

Instantly share code, notes, and snippets.

View srikrishnasakunia's full-sized avatar
:octocat:

Srikrishna Sakunia srikrishnasakunia

:octocat:
View GitHub Profile
@srikrishnasakunia
srikrishnasakunia / MainActivity.kt
Created December 29, 2022 12:24
Main Activity KT
// Retriving Using the Flow Method
lifecycleScope.launch {
preferenceDataStoreHelper.getPreference(NAME_KEY,"").collect {
name = it
}
}
// Retriving Using the Not Flow / static data Method
lifecycleScope.launch {
val name = preferenceDataStoreHelper.getFirstPreference(NAME_KEY,"")
@srikrishnasakunia
srikrishnasakunia / ViewModel.kt
Last active December 29, 2022 12:24
ViewModel
// Retriving Using the Flow Method
viewModelScope.launch {
preferenceDataStoreHelper.getPreference(NAME_KEY,"").collect {
name = it
}
}
// Retriving Using the Not Flow / static data Method
viewModelScope.launch {
val name = preferenceDataStoreHelper.getFirstPreference(NAME_KEY,"")
@srikrishnasakunia
srikrishnasakunia / PreferenceDataStoreHelper.kt
Created December 29, 2022 11:24
Implementation of Functions.
package com.example.datastoretest.data.local
import android.content.Context
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
@srikrishnasakunia
srikrishnasakunia / PreferenceDataStoreConstants.kt
Created December 29, 2022 10:54
This file consists of variables that will store the values.
package com.example.datastoretest.data.local
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
object PreferenceDataStoreConstants {
val IS_MINOR_KEY = booleanPreferencesKey("IS_MINOR_KEY")
val AGE_KEY = intPreferencesKey("AGE_KEY")
@srikrishnasakunia
srikrishnasakunia / IPreferenceDataStoreAPI.kt
Created December 29, 2022 10:08
This interface will consist of all our functions which will be implemented in our Helper class.
package com.example.datastoretest.data.local
import androidx.datastore.preferences.core.Preferences
import kotlinx.coroutines.flow.Flow
interface IPreferenceDataStoreAPI {
suspend fun <T> getPreference(key: Preferences.Key<T>,defaultValue: T):Flow<T>
suspend fun <T> getFirstPreference(key: Preferences.Key<T>,defaultValue: T):T
suspend fun <T> putPreference(key: Preferences.Key<T>,value:T)
suspend fun <T> removePreference(key: Preferences.Key<T>)