如何使用协程在 ViewModel 中正确实现 Result.Success 和 Result.failure?

问题描述

我有视图模型,我通过以下方式得到响应

@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()}");
            }

        }
    }



}

但我想添加 Result.Success 逻辑,如果它是错误 Result.Error 使用密封类我会成功

在我的 Repository 类下面

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

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

在我的 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>
}

在我的响应类下面

@Parcelize
data class GiphyResponse(

    @field:Serializedname("pagination")
    val pagination: Pagination,@field:Serializedname("data")
    val data: List<DataItem>,@field:Serializedname("Meta")
    val Meta: Meta
) : Parcelable

以下结果密封类

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

解决方法

更新您的 giphyresponse 变量:

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

到:

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

现在更新您在 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()}");
            }

        }
    }