How keep session active when user clicks checkbox compose

Viewed 34

I have been trying to implement a checked box where is user says keep me signed in they stay signed in. The problem however is I am wondering how can I store this value in the pref and and if its positive they just log in.

in my viewModel I have this function

 fun keepSignedIn(updatedValue: Boolean){
     keepSignedIn.value = updatedValue
 }

and in my content screen

@Composable
fun KeepMeSignedInCheckBox() {
  
    Checkbox(checked = state.keepMeSignedIn, onCheckedChange = keepMeSignedIn.invoke(it))
}

I am wondering what is the best way to update this value in the view Model? I have my login function in the view model too.

What I have tried,

fun keepSignedIn(updatedValue: Boolean){
    keepSignedIn.value = updatedValue
    val signedIn = instance().keepUserSignedIn
    if(signedIn){
        loginUser
    }
}

But my approach does not work when I leave the app it take me to login screen, and does not store that session.

1 Answers

Initialize the variable as

val sessionStored by mutableStateOf(
                        context.getSharedPreferences("prefs", Context.MODE_PRIVATE)
                               .getBoolean("isSessionStored", false)
                     )

Where "prefs" is the name you assigned to the preferences, MODE_PRIVATE is the mode of accessing the SharedPreferences, "isSessionStored" the name of the preference field and false its default value, for obvious reasons.

Use it like so

Checkbox(checked = state.sessionStored, onCheckedChange = viewModel::setSessionStored)

Define setSessionStored like so

fun setSessionStored(sessionStored: Boolean) {
  this.sessionStored = sessionStored
  context.getSharedPreferences("prefs", Context.MODE_PRIVATE)
         .edit()
         .putBoolean("isSessionStored", sessionStored)
         .apply()
}

'll Work like a charm,

Here's a piece to code to https://youtu.be/RsEoX0FbETI

Related