Untitled

Ini bagian view modelnya mas
mail@pastecode.io avatar
unknown
kotlin
2 years ago
2.7 kB
3
Indexable
Never
package com.example.githubuser.viewmodels

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.githubuser.model.UserItemResponse
import com.example.githubuser.network.ApiConfig
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class UserViewModel : ViewModel() {

    private val _listResponse = MutableLiveData<List<UserItemResponse>>()
    val listResponse: LiveData<List<UserItemResponse>> get() = _listResponse

    private val _detailResponse = MutableLiveData<UserItemResponse>()
    val detailResponse: LiveData<UserItemResponse> get() = _detailResponse

    private val _isLoading = MutableLiveData<Boolean>()
    val isLoading: LiveData<Boolean> get() = _isLoading

    companion object {
        private const val TAG = "UserViewModel"
    }

    init {
        getListResponse()
    }

    private fun getListResponse() {
        _isLoading.value = true
        val client = ApiConfig.getApiService().getUserList()
        client.enqueue(object: Callback<List<UserItemResponse>> {
            override fun onResponse(
                call: Call<List<UserItemResponse>>,
                response: Response<List<UserItemResponse>>
            ) {
                _isLoading.value = false
                if (response.isSuccessful) {
                    _listResponse.value = response.body()
                } else {
                    Log.e(TAG, "onFailure: ${response.message()}")
                }
            }

            override fun onFailure(call: Call<List<UserItemResponse>>, t: Throwable) {
                _isLoading.value = false
                Log.e(TAG, "onFailure: ${t.message.toString()}")
            }
        })
    }

    fun getDetailResponse(login: String) {
        _isLoading.value = true
        val client = ApiConfig.getApiService().getUserDetail(login)
        client.enqueue(object: Callback<UserItemResponse> {
            override fun onResponse(
                call: Call<UserItemResponse>,
                response: Response<UserItemResponse>
            ) {
                _isLoading.value = false
                if (response.isSuccessful) {
                    _detailResponse.value = response.body()
                } else {
                    Log.e(TAG, "onFailure: ${response.message()}")
                }
            }

            override fun onFailure(call: Call<UserItemResponse>, t: Throwable) {
                _isLoading.value = false
                Log.e(TAG, "onFailure: ${t.message.toString()}")
            }
        })
    }
}