Skip to content

Instantly share code, notes, and snippets.

@PatilShreyas
Last active Sep 16, 2021
Embed
What would you like to do?
@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