首页 > 解决方案 > 如何在 LiveData类中使用“I”作为具体类型参数?

问题描述

标签: androidfirebasekotlingenericsgoogle-cloud-firestore

解决方案


类的I类型不能被具体化,因此您不能I为该函数创建重载的具体化。我认为您可以通过使类成为构造函数参数来手动具体化类类型。像这样:

class ItemLiveData<I>(private val type: Class<I>): LiveData<I>() {

    override fun onEvent(querySnapshot: QuerySnapshot?, e: FirebaseFirestoreException?) {
        if (e != null) return

        for (documentChange in querySnapshot!!.documentChanges) {
            when (documentChange.type) {
                DocumentChange.Type.ADDED -> setValue(getItem(documentChange)) //Add to LiveData
            }
        }
    
    private fun getItem(doc: DocumentChange) = doc.document.toObject<I>(type)
}

推荐阅读