如何实现Result.成功和结果.在带有协同程序的ViewModel中是否正确失败



我有一个视图模型,我用以下方式得到响应

@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。成功逻辑如果我会成功,如果它是错误的结果。使用密封类时出错

低于我的存储库类

class GiphyTaskRepository
@Inject
constructor(private val giphyTaskApiService: GiphyTaskApiService)
{
suspend fun getGifsFromText(apikey:String,text:String,limit:Int)=
giphyTaskApiService.getGifsFromText(apikey,text,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()}");
}
}
}

相关内容

  • 没有找到相关文章

最新更新