gpt4 book ai didi

android - LiveData 不会将类型推断为所需的返回值

转载 作者:行者123 更新时间:2023-11-29 18:25:18 25 4
gpt4 key购买 nike

我已经拨通了emit()在我的 viewModel 中,但我不知道为什么我的 LiveDataScope返回 Resource<Any>当我定义了 Resource类型为 Artist

View 模型

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()
}

repo

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>> 来推断类型在我的 View 模型中,它提供了一个 Resource<Any>到 LiveData:

enter image description here

我在另一个类中实现了相同的方法,但 livedata 返回正常,我尝试清除缓存并重新启动、清理和重建,但它一直返回相同

为什么不能正确推断类型?

最佳答案

推断正确。您的代码向 Kotlin 建议 LiveData 可以产生两种不同类型的对象。你有这个:

emit(artistList)

还有这个:

emit(Resource.error("Error: ",e.message))

Kotlin 可以从中推断出的最具体的常见类型是 Resource<Any> ,因为它们都是 Resource 对象,但具有不同的通用类型。

考虑发出一个带有两个子类的密封类,一个用于数据类型,另一个用于错误类型。

关于android - LiveData 不会将类型推断为所需的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59430365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com