This commit is contained in:
Trey t
2025-11-04 15:41:03 -06:00
parent f2ade0a1e2
commit 219eaa69ee
17 changed files with 637 additions and 92 deletions

View File

@@ -2,8 +2,10 @@ package com.mycrib.android.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.mycrib.shared.models.AuthResponse
import com.mycrib.shared.models.LoginRequest
import com.mycrib.shared.models.RegisterRequest
import com.mycrib.shared.models.Residence
import com.mycrib.shared.network.ApiResult
import com.mycrib.shared.network.AuthApi
import com.mycrib.storage.TokenStorage
@@ -17,6 +19,9 @@ class AuthViewModel : ViewModel() {
private val _loginState = MutableStateFlow<ApiResult<String>>(ApiResult.Loading)
val loginState: StateFlow<ApiResult<String>> = _loginState
private val _registerState = MutableStateFlow<ApiResult<AuthResponse>>(ApiResult.Loading)
val registerState: StateFlow<ApiResult<AuthResponse>> = _registerState
fun login(username: String, password: String) {
viewModelScope.launch {
_loginState.value = ApiResult.Loading
@@ -35,7 +40,7 @@ class AuthViewModel : ViewModel() {
fun register(username: String, email: String, password: String) {
viewModelScope.launch {
_loginState.value = ApiResult.Loading
_registerState.value = ApiResult.Loading
val result = authApi.register(
RegisterRequest(
username = username,
@@ -43,11 +48,11 @@ class AuthViewModel : ViewModel() {
password = password
)
)
_loginState.value = when (result) {
_registerState.value = when (result) {
is ApiResult.Success -> {
// Store token for future API calls
TokenStorage.saveToken(result.data.token)
ApiResult.Success(result.data.token)
ApiResult.Success(result.data)
}
is ApiResult.Error -> result
else -> ApiResult.Error("Unknown error")
@@ -55,6 +60,10 @@ class AuthViewModel : ViewModel() {
}
}
fun resetRegisterState() {
_registerState.value = ApiResult.Loading
}
fun logout() {
viewModelScope.launch {
val token = TokenStorage.getToken()