android - 如何使用协程在 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 使用密封类
在我的存储库类下面
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()}");
}
}
}
推荐阅读
- python - Python:具有太多索引的数组?
- r - R中的多次for循环时间计算非常高
- javascript - 如何在数组映射循环中的redux saga中向firebase发出并行请求?
- c - time(NULL) 在 PIC-IoT WG 开发板上返回 0
- c++ - Arduino c ++缺少字符串的第一个字母
- oop - 为什么子模块可以使用祖先模块的私有项,反之不行?
- java - 使用多个关键字Java在数组中查找对象
- javascript - 不允许我设置 Javascript 创建的 div 的类名
- java - 我想在不使用数据结构的情况下动态设置/更新子对象
- python - CSV 写入 - 将行拆分为多列