Advertisement
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() {
- fun performLogin2(email: String, password: String): LiveData<ResultState<LoginResult>> =
- repository.login(email, password)
- // 1. Terapkan enkapsulasi. ViewModel memiliki state-nya sendiri.
- private val _loginResult = MediatorLiveData<ResultState<LoginResult>>()
- val loginResult: LiveData<ResultState<LoginResult>> = _loginResult
- // 2. Buat fungsi yang dipanggil UI untuk *memulai* proses login.
- // Fungsi ini tidak mengembalikan apa-apa (Unit).
- fun performLogin(email: String, password: String) {
- // Panggil fungsi repository yang mengembalikan LiveData
- val resultLiveData = repository.login(email, password)
- // 3. Tempelkan (source) LiveData dari repository ke LiveData internal ViewModel.
- _loginResult.addSource(resultLiveData) { result ->
- // 4. Update nilai LiveData internal dengan hasil dari repository.
- _loginResult.value = result
- // Hapus source setelah mendapatkan hasil agar tidak ada duplikasi observer
- _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
Advertisement