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

问题描述 投票:1回答:2

我在viewModel中调用了emit(),但是当我定义LiveDataScope的类型为Resource<Any>时,我不知道为什么我的Resource返回Artist

ViewModel

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

    }
}

UseCase

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>

enter image description here

我已经在另一个类中实现了相同的方式,但是livedata返回的很好,我尝试了清除缓存并重新启动,清理和重建,但一直保持不变

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

android firebase kotlin mvvm android-livedata
2个回答
2
投票
正确推断。您的代码向Kotlin建议LiveData可以产生两种不同类型的对象。你有这个:

0
投票
您可以按照Doug指出的将Resource实现更改为此
© www.soinside.com 2019 - 2024. All rights reserved.