Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hilt and Generic classes in ViewModels
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
}
@nyxee

This comment has been minimized.

Copy link
Owner Author

@nyxee nyxee commented Apr 7, 2021

I have failed to get the provider to work at the moment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment