Skip to content

Hilt ‐ multi binding IntoMap

Devrath edited this page Oct 9, 2023 · 4 revisions

Observation

  • IntoMap is used to inject several instances of different types with a single reference
  • An important thing to observe here is its key-value pairs.
  • @ClassKey denotes the key for an Instance and the value would be the Instance.
  • All the instances will have the same same Interface as return type, so we just inject that Interface as a HashMap as shown below
  • Then we can get the key,value by looping like a normal HashMap

Output

<------------------------------------>
KEY:->class com.istudio.di.modules.hilt.demos.multibinding_demo.into_map_demo.implementations.HassanCity
VALUE:->com.istudio.di.modules.hilt.demos.multibinding_demo.into_map_demo.implementations.HassanCity@3cd3875
56848944
<------------------------------------>
<------------------------------------>
KEY:->class com.istudio.di.modules.hilt.demos.multibinding_demo.into_map_demo.implementations.BangaloreCity
VALUE:->com.istudio.di.modules.hilt.demos.multibinding_demo.into_map_demo.implementations.BangaloreCity@512e00a
237385104
<------------------------------------>

Code

Implementation

City.kt

interface City {
    fun printInstance(name:String)
}

HassanCity.kt

class HassanCity @Inject constructor() : City {
    override fun printInstance(name: String) { }
}

BangaloreCity.kt

class BangaloreCity @Inject constructor() : City {
    override fun printInstance(name: String) { }
}

Modules

HiltCityModule.kt

@InstallIn(SingletonComponent::class)
@Module
abstract class HiltCityModule {

    @Multibinds
    abstract fun multiBindsCityProviders(): Map<Class<*>, City>

    @Binds
    @IntoMap
    @ClassKey(HassanCity::class)
    abstract fun provideHassanCity(impl: HassanCity) : City

    @Binds
    @IntoMap
    @ClassKey(BangaloreCity::class)
    abstract fun provideBangaloreCity(impl: BangaloreCity) : City

}

Activity

MyActivity.kt

@AndroidEntryPoint
class MyActivity : AppCompatActivity() {

    private lateinit var binding: ActivityHiltMultiBindingsSelectionBinding
    @Inject lateinit var cities : Map<Class<*>,@JvmSuppressWildcards City>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityHiltMultiBindingsSelectionBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setOnClickListeners();
    }

    private fun setOnClickListeners() {
        binding.apply {
            intoMapId.setOnClickListener {
                cities.forEach { city ->
                    PrintUtils.printLog("<------------------------------------>")
                    PrintUtils.printLog("KEY:->"+city.key)
                    PrintUtils.printLog("VALUE:->"+city.value)
                    PrintUtils.printLog(city.hashCode().toString())
                    PrintUtils.printLog("<------------------------------------>")
                }
            }
        }
    }
}
Clone this wiki locally