Skip to content

Instantly share code, notes, and snippets.

@pavan5208
Created July 14, 2021 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pavan5208/d973dcae1e37d3033b328ef8fe43517d to your computer and use it in GitHub Desktop.
Save pavan5208/d973dcae1e37d3033b328ef8fe43517d to your computer and use it in GitHub Desktop.
package com.sample.android_sample_preference_datastore.proto
import androidx.datastore.core.DataStore
import com.sample.android_sample_preference_datastore.UserStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import java.io.IOException
class ProtoUserRepoImpl(private val protoDataStore: DataStore<UserStore>) :ProtoUserRepo {
override suspend fun saveUserLoggedInState(state: Boolean) {
protoDataStore.updateData {store ->
store.toBuilder()
.setIsLoggedIn(state)
.build()
}
}
override suspend fun getUserLoggedInState(): Flow<Boolean> {
return protoDataStore.data
.catch { exception ->
// dataStore.data throws an IOException when an error is encountered when reading data
if (exception is IOException) {
emit(UserStore.getDefaultInstance())
} else {
throw exception
}
}.map { protoBuilder ->
protoBuilder.isLoggedIn
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment