eveeeeef21

BelajarMediatorLive

Jun 29th, 2025 (edited)
1,707
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 2.11 KB | Source Code | 0 0
  1. package com.example.storyapp.ui.login
  2.  
  3. import androidx.lifecycle.LiveData
  4. import androidx.lifecycle.MediatorLiveData
  5. import androidx.lifecycle.ViewModel
  6. import com.example.storyapp.data.response.auth.LoginResult
  7. import com.example.storyapp.di.Repository
  8. import com.example.storyapp.utils.ResultState
  9.  
  10. class LoginViewModel(private val repository: Repository) : ViewModel() {
  11.  
  12.     private val _loginResult = MediatorLiveData<ResultState<LoginResult>>()
  13.     val loginResult: LiveData<ResultState<LoginResult>> = _loginResult
  14.  
  15.     fun performLogin(email: String, password: String) {
  16.         val resultLiveData = repository.login(email, password) // return LiveData
  17.  
  18.         _loginResult.addSource(resultLiveData) { result ->
  19.             _loginResult.value = result
  20.             if (result is ResultState.Success || result is ResultState.Error) {
  21.                 _loginResult.removeSource(resultLiveData)
  22.             }
  23.         }
  24.     }
  25. }
  26.  
  27.  
  28.  
  29. // di kelas Repository
  30. fun login(
  31.         email: String,
  32.         password: String
  33.     ): LiveData<ResultState<LoginResult>> = liveData {
  34.         emit(ResultState.Loading)
  35.         try {
  36.             val response = apiService.login(email, password)
  37.             if (!response.error) {
  38.                 val loginResult = response.loginResult
  39.                 userPreference.saveSession(loginResult) // Menyimpan data login ke sesi
  40.                 emit(ResultState.Success(loginResult))
  41.             } else {
  42.                 emit(ResultState.Error(ErrorType.ApiError(response.message)))
  43.             }
  44.         } catch (e: HttpException) {
  45.             if (e.code() == 401) {
  46.                 emit(ResultState.Error(ErrorType.ResourceError(R.string.error_wrong_credentials)))
  47.             } else {
  48.                 val errorBody = e.response()?.errorBody()?.string()
  49.                 val errorResponse = Gson().fromJson(errorBody, LoginResponse::class.java)
  50.                 emit(ResultState.Error(ErrorType.ApiError(errorResponse.message)))
  51.             }
  52.         } catch (e: Exception) {
  53.             emit(ResultState.Error(ErrorType.ResourceError(R.string.login_failed)))
  54.         }
  55.     }
Advertisement
Add Comment
Please, Sign In to add comment