Skip to content

Hilt ‐ multi binding IntoSet

Devrath edited this page Oct 9, 2023 · 5 revisions

Observation

Output

<------------------------------------>
211308169
COUNTRY INSTANCE:->211308169
COUNTRY:-> com.istudio.di.modules.hilt.demos.multibinding_demo.into_set_demo.implementations.America@c984e89
<------------------------------------>
<------------------------------------>
196959886
COUNTRY INSTANCE:->196959886
COUNTRY:-> com.istudio.di.modules.hilt.demos.multibinding_demo.into_set_demo.implementations.Russia@bbd5e8e
<------------------------------------>

Code

Implementation

Country.kt

interface Country {
    fun printInstance(name:String)
}

Russia.kt

class Russia @Inject constructor() : Country {
    override fun printInstance(name: String) {

    }
}

America.kt

class America @Inject constructor() : Country {
    override fun printInstance(name: String) {

    }
}

Modules

HiltCountryModule.kt

@InstallIn(SingletonComponent::class)
@Module
interface HiltCountryModule {

    @Binds
    @IntoSet
    fun bindAmerica(country : America) : Country

    @Binds
    @IntoSet
    fun bindRussia(country : Russia) : Country

}

Activity

MyActivity.kt

@AndroidEntryPoint
class MyActivity : AppCompatActivity() {

    private lateinit var binding: ActivityHiltMultiBindingsSelectionBinding
 
    @Inject lateinit var countries : Set<@JvmSuppressWildcards Country>

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

    private fun setOnClickListeners() {
        binding.apply {
            usingIntoSetId.setOnClickListener {
                countries.forEach { country ->
                    PrintUtils.printLog("<------------------------------------>")
                    PrintUtils.printLog(country.hashCode().toString())
                    PrintUtils.printLog("COUNTRY INSTANCE:->${country.hashCode()}")
                    PrintUtils.printLog("COUNTRY:-> $country")
                    PrintUtils.printLog("<------------------------------------>")
                }
            }
        }
    }
}
Clone this wiki locally