So, I’ve defined a simple data class, as follows:
@Serializable
data class UserSession(
var name: String = "",
val isEnrolled: Boolean = false,
)
This class relates to another Kotlin class, UserSessionViewModel, as follows:
class UserSessionViewModel(
private val application: Application,
private val store: DataStore<UserSession>,
) : AndroidViewModel(application), KoinComponent {
/**
* A [Flow] representing the current [UserSession].
* It emits every time the user session is updated.
*/
val userSession: Flow<UserSession>
get() = store.data
/**
* Enrolls the user in the application.
* Updates the `isEnrolled` property of [UserSession] to true.
*/
fun enroll() {
viewModelScope.launch {
store.updateData {
it.copy(isEnrolled = true)
}
}
}
/**
* Caches the given name in the [UserSession].
*
* @param name The name to be cached.
*/
fun cacheName(name: String) {
viewModelScope.launch {
store.updateData {
it.copy(name = name)
}
}
}
fun getEnrolledName(): String {
viewModelScope.launch {
store.<proper-method?> {
//what do I do here to return the 'name' variable's value?
}
}
//and other, similar write-only methods into the data-store
}
My question: how would I implement a simple ‘getter’ method into one of these variables? Or, is there a need to do so?
The other examples I’ve found always talk about implementing a Preferences DataStore…this isn’t quite the case. I just want to make sure my variable of interest, persists across app restarts, and can be read within my UserSessionViewModel object’s methods
Thanks in advance,
Charles.
2