Skip to content

Instantly share code, notes, and snippets.

@rommansabbir
Last active Mar 18, 2022
Embed
What would you like to do?
Android - Hilt: Inject multiple instances of SameType Object to the Dependent Module
package com.amiprobashi.root
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