Android - Hilt: Inject multiple instances of SameType Object to the Dependent Module
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
import androidx.fragment.app.Fragment | |
import androidx.lifecycle.ViewModel | |
import dagger.Module | |
import dagger.Provides | |
import dagger.hilt.InstallIn | |
import dagger.hilt.android.components.ViewModelComponent | |
import dagger.hilt.android.lifecycle.HiltViewModel | |
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 { | |
@Volatile | |
var userId: Int = -1 | |
@Volatile | |
var profileId: Int = -1 | |
} | |
@Module | |
@InstallIn(ViewModelComponent::class) | |
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.*/ | |
@Provides | |
@Named("userId") | |
fun provideUserId(): Int = DataHolder.userId | |
@Provides | |
@Named("profileId") | |
fun provideProfileId(): Int = DataHolder.profileId | |
} | |
@HiltViewModel | |
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