add a logout button that clears datastore when tapped

This commit is contained in:
Satindar Dhillon
2022-08-16 21:35:20 -07:00
parent f7dfb21f4f
commit 53cb16bd2a
3 changed files with 21 additions and 4 deletions

View File

@ -19,6 +19,7 @@ private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(
interface DatastoreRepository {
val hasAuthTokenFlow: Flow<Boolean>
suspend fun clear()
suspend fun putString(key: String, value: String)
suspend fun putInt(key: String, value: Int)
suspend fun getString(key: String): String?
@ -54,6 +55,10 @@ class OmnivoreDatastore @Inject constructor(
return preferences[preferencesKey]
}
override suspend fun clear() {
context.dataStore.edit { it.clear() }
}
override val hasAuthTokenFlow: Flow<Boolean> = context
.dataStore.data.map { preferences ->
val key = stringPreferencesKey(DatastoreKeys.omnivoreAuthToken)

View File

@ -48,4 +48,10 @@ class LoginViewModel @Inject constructor(
}
}
}
fun logout() {
viewModelScope.launch {
datastoreRepo.clear()
}
}
}

View File

@ -37,7 +37,7 @@ class MainActivity : ComponentActivity() {
OmnivoreTheme {
// A surface container using the 'background' color from the theme
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background) {
rootView(viewModel)
RootView(viewModel)
}
}
}
@ -45,18 +45,18 @@ class MainActivity : ComponentActivity() {
}
@Composable
fun rootView(viewModel: LoginViewModel) {
fun RootView(viewModel: LoginViewModel) {
val hasAuthToken: Boolean by viewModel.hasAuthTokenLiveData.observeAsState(false)
if (hasAuthToken) {
loggedInView()
LoggedInView(viewModel)
} else {
LoginView(viewModel)
}
}
@Composable
fun loggedInView() {
fun LoggedInView(viewModel: LoginViewModel) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
@ -65,6 +65,12 @@ fun loggedInView() {
.fillMaxSize()
) {
Text("You have a valid auth token. Nice. Go save something in Chrome!")
Button(onClick = {
viewModel.logout()
}) {
Text(text = "Logout")
}
}
}