Skip to content

Instantly share code, notes, and snippets.

View vaibhavgoyal09's full-sized avatar
:octocat:
Learning by building stuff

Vaibhav Goyal vaibhavgoyal09

:octocat:
Learning by building stuff
View GitHub Profile
@HiltAndroidApp
class BaseApplication : Application()
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mystikcoder.datastore">
<application
android:name=".BaseApplication"
android:allowBackup="false"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
interface DataStoreRepository {
suspend fun putString(key: String, value: String)
suspend fun putInt(key: String, value: Int)
suspend fun getString(key: String): String?
suspend fun getInt(key: String): Int?
}
class DataStoreRepositoryImpl : DataStoreRepository {
override suspend fun putString(key: String, value: String) {
}
override suspend fun putInt(key: String, value: Int) {
}
private const val PREFERENCES_NAME = "my_preferences"
private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = PREFERENCES_NAME)
class DataStoreRepositoryImpl @Inject constructor(
private val context: Context
) : DataStoreRepository {
override suspend fun putString(key: String, value: String) {
val preferencesKey = stringPreferencesKey(key)
override suspend fun putString(key: String, value: String) {
val preferencesKey = stringPreferencesKey(key)
context.dataStore.edit { preferences ->
preferences[preferencesKey] = value
}
}
override suspend fun putInt(key: String, value: Int) {
val preferencesKey = intPreferencesKey(key)
context.dataStore.edit { preferences ->
override suspend fun getString(key: String): String? {
return try {
val preferencesKey = stringPreferencesKey(key)
val preferences = context.dataStore.data.first()
preferences[preferencesKey]
}catch (e: Exception){
e.printStackTrace()
null
}
}
@HiltViewModel
class DataViewModel @Inject constructor(
private val repository: DataStoreRepository
) : ViewModel() {
fun saveName(value: String) {
viewModelScope.launch {
repository.putString(NAME, value)
}
}
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Singleton
@Provides
fun provideDataStoreRepository(
@ApplicationContext app: Context
): DataStoreRepository = DataStoreRepositoryImpl(app)
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
tools:context=".presentation.activity.MainActivity">
<LinearLayout