Skip to content

Instantly share code, notes, and snippets.

@nyxee
Last active April 7, 2021 10:53
Show Gist options
  • Save nyxee/bfb2fd3b2a29d886479f5bc54d836e36 to your computer and use it in GitHub Desktop.
Save nyxee/bfb2fd3b2a29d886479f5bc54d836e36 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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