我已经在viewModel中调用了emit()
,但是当我定义LiveDataScope
的类型时,我不知道为什么我的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)
}
}
但是由于某些原因,它没有在我的视图模型中使用Resource<MutableList<Artist>>
来推断类型,而是为LiveData提供了Resource<Any>
:
我已经在另一个类中实现了相同的方式,但是livedata返回的很好,我尝试了清除缓存并重新启动,清理和重建,但是它始终返回相同的结果
为什么不能正确推断类型?
答案 0 :(得分:2)
正确推断。您的代码向Kotlin建议LiveData可以产生两种不同类型的对象。你有这个:
emit(artistList)
这:
emit(Resource.error("Error: ",e.message))
Kotlin可以从中推断出的最具体的常见类型是Resource<Any>
,因为它们都是Resource对象,但是具有不同的泛型类型。
请考虑发出带有两个子类的密封类,一个子类用于数据类型,另一个子类用于错误类型。
答案 1 :(得分:0)
您可以按照Doug指出的将Resource
实现更改为此
sealed class Resource<out T> {
class Loading<out T> : Resource<T>()
data class Success<out T>(val data: T) : Resource<T>()
data class Failure<out T>(val throwable: Throwable) : Resource<T>()
}