Last active
April 7, 2021 10:53
-
-
Save nyxee/bfb2fd3b2a29d886479f5bc54d836e36 to your computer and use it in GitHub Desktop.
Hilt and Generic classes in ViewModels
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ClubsViewModel<T> @ViewModelInject constructor(clazz: Class<T>) : BaseViewModel<T>(clazz) { | |
listenToFireStoreCollection("Clubs", _mClubs) | |
... | |
} | |
class BViewModel<T> @ViewModelInject constructor(clazz: Class<T>) : BaseViewModel<T>(clazz) { | |
private var _mBs = MutableLiveData<List<T>>() | |
listenToFireStoreCollection("Bname", _mBs) | |
... | |
} | |
class BaseViewModel<T> @ViewModelInject constructor(val clazz: Class<T>) { | |
protected val mFirestore = Firebase.firestore | |
protected fun listenToFireStoreCollection(val collectionName: String, liveData: MutableLiveData<List<T>>) | |
mFirestore.collection(collectionName).addSnapshotListener { snapshot, e -> | |
if (e != null) { | |
return@addSnapshotListener | |
} | |
if (snapshot != null) { | |
liveData.value = snapshot.documents.mapNotNull { it.toObject(clazz) } | |
} | |
} | |
} | |
} | |
//FRAGMENT EXAMPLES. | |
@AndroidEntryPoint | |
class ClubsFragment : Fragment() { | |
private val mClubsViewModel: ClubsViewModel<ClubsFSEntity> by viewModels() | |
... | |
} | |
@AndroidEntryPoint | |
class BsFragment : Fragment() { | |
private val mBsViewModel: BsViewModel<BsFSEntity> by viewModels() | |
... | |
} | |
-------------------------------------------------------------------------- | |
//TRYING TO CREATE A HILT PROVIDER | |
@Module | |
@InstallIn(ApplicationComponent::class) | |
object FragmentModule { | |
@Singleton | |
@Provides | |
inline fun <reified T> provideVMEntityClass(): Class<T> = T::class.java | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have failed to get the provider to work at the moment.