My LoginRepository
interface LoginRepository {
suspend fun postLogin(
loginRequest: LoginRequest
): Resource<Login>
}
My LoginRepoImpl
@Singleton
class LoginRepositoryImpl @Inject constructor(
private val api:ApiClient,
):LoginRepository{
override suspend fun postLogin(loginRequest: LoginRequest): Resource<Login> {
return try {
val result = api.login(loginRequest)
Resource.Success(result.toLoginDomain())
}catch (e: IOException){
e.printStackTrace()
Resource.Error("Could not load login")
}catch (e:HttpException){
e.printStackTrace()
Resource.Error("Internet connection problem")
}
}
}
My ViewModel
@HiltViewModel
class LoginViewModel @Inject constructor(
private val useCase: LoginUseCase
) : ViewModel() {
private val _state = mutableStateOf<LoginState>(LoginState.InProgress)
val state: State<LoginState> get() = _state
fun login(username: String, password: String) = viewModelScope.launch {
val login = async { useCase.execute(loginRequest = LoginRequest(username,password)) }
_state = _state.value
}
Please help me, i have no idea, sorry i just startd my career as android developer 1 month ago. so i am new in android development.
CodePudding user response:
You just need a small improvement in your viewModel:
@HiltViewModel
class LoginViewModel @Inject constructor(
private val useCase: LoginUseCase
) : ViewModel() {
private val _state = mutableStateOf<LoginState>(LoginState.InProgress)
val state: State<LoginState> get() = _state
fun login(username: String, password: String) = viewModelScope.launch {
val loginDeferred = async { useCase.execute(loginRequest = LoginRequest(username,password)) }
when (loginDeferred.await()) {
is Resource.Success -> _state.value = LoginState.Success
is Resource.Error -> _state.value = LoginState.Error
}
}
}
What have we done there? We are waiting to login result via await
operator. After that we push new LoginState
depending on result.