This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@HiltViewModel | |
class UserViewModel @Inject constructor( | |
application: Application, | |
private val userRepository: UserRepository | |
) : AndroidViewModel(application) { | |
/** | |
* A [SharedPreferences] for storing user preferences. | |
*/ | |
private val userPreferences = application.getSharedPreferences( | |
UserPreferences.NAME, | |
Context.MODE_PRIVATE | |
) | |
// ... | |
// OTHER CODE HERE | |
// ... | |
/** | |
* Creates a new user with [name] and [email] and sets active session of that created user. | |
*/ | |
fun setUserSession(name: String, email: String) { | |
viewModelScope.launch { | |
val user = userRepository.add(name, email) | |
withContext(Dispatchers.IO) { | |
userPreferences.edit { | |
putInt(UserPreferences.Keys.ID, user.id) | |
putString(UserPreferences.Keys.NAME, user.name) | |
putString(UserPreferences.Keys.EMAIL, user.email) | |
} | |
} | |
// Update LiveData/StateFlow/Rx or any other stream | |
} | |
} | |
/** | |
* Object holding user preference key details | |
*/ | |
private object UserPreferences { | |
const val NAME = "user_pref" | |
object Keys { | |
const val ID = "user_id" | |
const val NAME = "user_name" | |
const val EMAIL = "user_email" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment