1

I have viewmodel where I am getting response with following way

@HiltViewModel
class GiphyTaskViewModel
@Inject
constructor(private val giphyTaskRepository: GiphyTaskRepository):ViewModel()
{
    var giphyresponse=MutableLiveData<List<DataItem>>()



    fun getGifsFromText(apikey:String,text:String,limit:Int)= viewModelScope.launch {
        giphyTaskRepository.getGifsFromText(apikey,text,limit).let { response->
            if(response?.isSuccessful){
                var list=response.body()?.data
                giphyresponse.postValue(list)
            }else{
                Log.d("TAG", "getGifsFromText: ${response.message()}");
            }

        }
    }



}

but I want to add Result.Success logic if I will get successfully if it is error Result.Error using sealed class

below my Repository class

class GiphyTaskRepository
@Inject
constructor(private val giphyTaskApiService: GiphyTaskApiService)
{

    suspend fun getGifsFromText(apikey:String,text:String,limit:Int)=
        giphyTaskApiService.getGifsFromText(apikey,text,limit)
}

below my getResponse

interface GiphyTaskApiService {

    @GET("gifs/search")
    suspend fun getGifsFromText(
        @Query("api_key") api_key:String,
        @Query("q") q:String ,
        @Query("limit") limit:Int
    ):Response<GiphyResponse>
}

below my Response class

@Parcelize
data class GiphyResponse(

    @field:SerializedName("pagination")
    val pagination: Pagination,

    @field:SerializedName("data")
    val data: List<DataItem>,

    @field:SerializedName("meta")
    val meta: Meta
) : Parcelable

below Result sealed class

sealed class Result
data class Success(val data: Any) : Result()
data class Error(val exception: Exception) : Result()

1 Answers1

0

Update your giphyresponse variable from:

var giphyresponse=MutableLiveData<List<DataItem>>()

to:

var giphyresponse=MutableLiveData<Result<List<DataItem>>>()

Now update your function in the GiphyTaskViewModel:

   fun getGifsFromText(apikey:String,text:String,limit:Int)= viewModelScope.launch {
        giphyTaskRepository.getGifsFromText(apikey,text,limit).let { response->
            if(response?.isSuccessful){
                var list=response.body()?.data
                giphyresponse.postValue(Success(list))
            }else{
               giphyresponse.postValue(Error(Exception(response.message())))
                Log.d("TAG", "getGifsFromText: ${response.message()}");
            }

        }
    }
Alpha 1
  • 4,118
  • 2
  • 17
  • 23