make loading seamless

This commit is contained in:
Minecon724 2024-08-04 09:36:07 +02:00
parent 5b27c8783e
commit 18dea0beb1
Signed by: Minecon724
GPG key ID: 3CCC4D267742C8E8
2 changed files with 27 additions and 20 deletions

View file

@ -107,7 +107,13 @@ class LoginActivity : ComponentActivity() {
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
LoginApp(loginViewModel)
val loading by loginViewModel.fullscreenLoading.collectAsState()
if (loading) {
CircularProgressIndicator()
} else {
LoginApp(loginViewModel)
}
}
}
}

View file

@ -31,25 +31,12 @@ class LoginViewModel(
private val _apiKey = MutableStateFlow<String>("")
var apiKey: StateFlow<String> = _apiKey.asStateFlow()
private val _fullscreenLoading = MutableStateFlow<Boolean>(false)
var fullscreenLoading: StateFlow<Boolean> = _fullscreenLoading.asStateFlow()
private val applicationContext = getApplication<Application>().applicationContext
private val sharedPreferences = applicationContext.getSharedPreferences("login", Context.MODE_PRIVATE)
fun loadKey() {
val apiKey = sharedPreferences.getString("apiKey", null)
if (apiKey != null) {
_apiKey.value = apiKey
tryLogin(LoginUiState.FullLoading)
}
}
fun tryLogin() {
tryLogin(LoginUiState.Loading)
}
fun onApiKeyChange(apiKey: String) {
_apiKey.update { apiKey }
}
private fun saveKey() {
with (sharedPreferences.edit()) {
@ -58,7 +45,17 @@ class LoginViewModel(
}
}
private fun tryLogin(initialState: LoginUiState) {
fun loadKey() {
val apiKey = sharedPreferences.getString("apiKey", null)
if (apiKey != null) {
_apiKey.value = apiKey
_fullscreenLoading.value = true
tryLogin()
}
}
fun tryLogin() {
val apiKey = apiKey.value
val vastApi = VastApi(apiKey, cronetEngine, executor)
@ -69,12 +66,16 @@ class LoginViewModel(
_uiState.value = LoginUiState.Success(user)
}, { apiFailure ->
_uiState.value = LoginUiState.Idle
_fullscreenLoading.value = false
_error.postValue(apiFailure.errorMessage)
})
)
_uiState.value = initialState
_uiState.value = LoginUiState.Loading
request.start()
}
fun onApiKeyChange(apiKey: String) {
_apiKey.update { apiKey }
}
}