android - LiveData 不会将类型推断为所需的返回值
问题描述
我已经emit()
在我的 viewModelLiveDataScope
中调用Resource<Any>
了Resource
Artist
视图模型
class EventsViewModel(private val useCase: Events):ViewModel() {
val fetchArtistList = liveData(Dispatchers.IO){
try {
val artistList = useCase.getEvents()
emit(artistList)
}catch (e:Exception){
Crashlytics.logException(e.cause)
emit(Resource.error("Error: ",e.message))
}
}
}
用例
class EventsImpl(private val eventsRepo:EventsRepo): Events {
override suspend fun getEvents(): Resource<MutableList<Artist>> = eventsRepo.getEventsDB()
}
回购
class EventsRepoImpl : EventsRepo {
override suspend fun getEventsDB(): Resource<MutableList<Artist>> {
val artistList = mutableListOf<Artist>()
val resultList = FirebaseFirestore.getInstance()
.collection("events")
.get().await()
for (document in resultList) {
val photoUrl = document.getString("photoUrl")
val artistName = document.getString("artistName")
val place = document.getString("place")
val time = document.getString("time")
val day = document.getLong("day")
artistList.add(Artist(photoUrl!!, artistName!!, time!!, place!!, day!!))
}
return Resource.success(artistList)
}
}
但由于某种原因,它没有在我的视图模型中推断类型,而是为LiveDataResource<MutableList<Artist>>
提供了一个:Resource<Any>
我在另一个类中实现了相同的方式,但 livedata 返回正常,我尝试清除缓存并重新启动、清理和重建,但它一直返回相同
为什么不能正确推断类型?
解决方案
它推断正确。您的代码向 Kotlin 建议 LiveData 可以产生两种不同类型的对象。你有这个:
emit(artistList)
和这个:
emit(Resource.error("Error: ",e.message))
Kotlin 可以从中推断出的最具体的常见类型是Resource<Any>
,因为它们都是 Resource 对象,但具有不同的泛型类型。
考虑改为发出一个带有两个子类的密封类,一个用于数据类型,另一个用于错误类型。
推荐阅读
- javascript - 如果 n 个字符串包含特定的输入字符并且仅将匹配的字符串列表数组存储在新数组中,如何传递条件语句?
- cypress - 安装 cypress 版本时导航器未定义错误
- sql - 如何将oracle中的行转换为特定的列集?
- redis - grpc_message":"在 'projects/xxx/locations/xxx/instances/xxx' 上的权限 'redis.instances.get' 被拒绝
- c# - sql中的批量比较
- node.js - 未捕获的 TypeError:setPrototypeOf 不是函数
- fortran - 如何确保 do 语句中的所有代码都由一个线程在 Fortran 中使用 omp_lib 执行?
- angular - 成功构建Angular后需要将dist文件夹复制到另一个文件夹
- mysql - 我需要使用 sql 查询根据 orderId 获取最后创建的合格乘客 ID 和 ping 乘客 ID
- php - 使用 php 和 VS Code 在 mysql 中显示 مريÙ