How can I retrieve the “energy” variable from my roomDatabase if I need the email to retrieve it and the email is found after I initialize my roomDatabase in my mainActivity?
Here is my room database
class RoomViewModel(private val repository: Repository) : ViewModel() {
val energyState: StateFlow<Int?> = repository.getEnergy(email)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = null,
)
fun updateEnergy(energy: Int, email: String) {
viewModelScope.launch {
repository.updateEnergy(energy, email)
}
}
Before everything worked great because I didn’t need an email, it just took the first entry like this :
@Query("SELECT energy FROM info LIMIT 1")
fun getEnergy(): Flow<Int>
Now i changed it to
@Query("SELECT energy FROM info WHERE email = :email LIMIT 1")
fun getEnergy(email: String): Flow<Int>
because I want the value associated with my email, but now the energyState value is set to null because I don’t have an email yet.
My screen pattern goes like this MainActivity (roomDatabase initialized) -> ChooseSignInMethod -> LoginScreen (insert email) or gameScreen (authentification verified with FirebaseAuth)
But I only have the email in my loginScreen or with a FireBaseAuth class like this :
fun checkAutStatus(){
val currentUser = aut.currentUser
if(currentUser == null) {
_authState.value = AuthState.Unauthenticated
}else{
_email.value = currentUser.email
_authState.value = AuthState.Authenticated
}
}
and it sets the _email.value of my signInViewModel like this
class SignInViewModel(private val aut: FirebaseAuth): ViewModel(){
private val _authState = MutableLiveData<AuthState>()
val authState: LiveData<AuthState> = _authState
private val _email = MutableStateFlow<String?>("Lavoe")
val email = _email.asStateFlow()
but now I can’t retrieve my energy, because i need the energy value to update it during the game with this method
fun updateEnergy(energy: Int, email: String) {
viewModelScope.launch {
repository.updateEnergy(energy, email)
}
}
So how can I set the value of
val energyState: StateFlow<Int?> = repository.getEnergy(email)
.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = null,
)
at the opening of my app with the energy value of my room database associated with my email address I received at the sign In to prevent from receiving a null value?
I have been trying to fiddle with the data types and different functions I wrote to retrieve the data but I just don’t know how to assign an Int or a Flow to another flow.