首页 > 解决方案 > LiveData 不会将类型推断为所需的返回值

问题描述

我已经emit()在我的 viewModelLiveDataScope中调用Resource<Any>ResourceArtist

视图模型

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 返回正常,我尝试清除缓存并重新启动、清理和重建,但它一直返回相同

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

标签: androidfirebasekotlinmvvmandroid-livedata

解决方案


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

emit(artistList)

和这个:

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

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

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


推荐阅读