【问题标题】:LiveData does not infer the type to desired return valueLiveData 不会将类型推断为所需的返回值
【发布时间】:2020-04-13 06:27:49
【问题描述】:

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

视图模型

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&lt;MutableList&lt;Artist&gt;&gt; 推断类型,而是为 LiveData 提供了 Resource&lt;Any&gt;

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

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

【问题讨论】:

    标签: android firebase kotlin mvvm android-livedata


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      emit(artistList)
      

      还有这个:

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

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

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

      【讨论】:

      • 你能帮我处理一下密封类 doug 吗?谢谢
      • 那里有很多文档。我建议研究一下,然后在遇到具体问题时提出一个新问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多