Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.storyapp.ui.login
- import androidx.lifecycle.LiveData
- import androidx.lifecycle.MediatorLiveData
- import androidx.lifecycle.ViewModel
- import com.example.storyapp.data.response.auth.LoginResult
- import com.example.storyapp.di.Repository
- import com.example.storyapp.utils.ResultState
- class LoginViewModel(private val repository: Repository) : ViewModel() {
- private val _loginResult = MediatorLiveData<ResultState<LoginResult>>()
- val loginResult: LiveData<ResultState<LoginResult>> = _loginResult
- fun performLogin(email: String, password: String) {
- val resultLiveData = repository.login(email, password) // return LiveData
- _loginResult.addSource(resultLiveData) { result ->
- _loginResult.value = result
- if (result is ResultState.Success || result is ResultState.Error) {
- _loginResult.removeSource(resultLiveData)
- }
- }
- }
- }
- // di kelas Repository
- fun login(
- email: String,
- password: String
- ): LiveData<ResultState<LoginResult>> = liveData {
- emit(ResultState.Loading)
- try {
- val response = apiService.login(email, password)
- if (!response.error) {
- val loginResult = response.loginResult
- userPreference.saveSession(loginResult) // Menyimpan data login ke sesi
- emit(ResultState.Success(loginResult))
- } else {
- emit(ResultState.Error(ErrorType.ApiError(response.message)))
- }
- } catch (e: HttpException) {
- if (e.code() == 401) {
- emit(ResultState.Error(ErrorType.ResourceError(R.string.error_wrong_credentials)))
- } else {
- val errorBody = e.response()?.errorBody()?.string()
- val errorResponse = Gson().fromJson(errorBody, LoginResponse::class.java)
- emit(ResultState.Error(ErrorType.ApiError(errorResponse.message)))
- }
- } catch (e: Exception) {
- emit(ResultState.Error(ErrorType.ResourceError(R.string.login_failed)))
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment