Skip to content

Instantly share code, notes, and snippets.

Last active October 3, 2022 12:08
What would you like to do?
Android - Hilt: Inject multiple instances of SameType Object to the Dependent Module
import androidx.lifecycle.ViewModel
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import javax.inject.Inject
import javax.inject.Named
/*Store the data in a singleton object so and mark the required objects as @Volatile
so that it can be stored in the main memory and every client receive the same instance.
We are assuming that *userId* is required for some APIs calling.*/
object DataHolder {
var userId: Int = -1
var profileId: Int = -1
object ViewModelComponent {
/*We can provide multiple instances for same type object with @Named.
Pass a unique key to receive the *Int* object in the dependent module.*/
fun provideUserId(): Int = DataHolder.userId
fun provideProfileId(): Int = DataHolder.profileId
class ExampleViewModel @Inject constructor(
@Named("userId") private val userId: Int,
@Named("profileId") private val profileId: Int
) :
ViewModel() {
init {
println("$userId, $profileId provided by Hilt")
class TestFragment : Fragment() {
companion object {
fun newInstance(userId: Int, profileId: Int): TestFragment {
/*Store the user id to the *DataHolder**/
DataHolder.userId = userId
DataHolder.profileId = profileId
return TestFragment()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment