Skip to content

Instantly share code, notes, and snippets.

@rommansabbir
Last active November 10, 2023 21:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rommansabbir/e14f93d37a334c2d3f778f874cbdd7dc to your computer and use it in GitHub Desktop.
Save rommansabbir/e14f93d37a334c2d3f778f874cbdd7dc to your computer and use it in GitHub Desktop.
Android - Hilt: Inject multiple instances of SameType Object to the Dependent Module
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