-
[Android] Dagger2 Multi binding 멀티바인딩(Set, Map)프로그래밍/Android 2022. 4. 24. 18:47
Dagger의 멀티바인딩을 사용하면 여러 모듈에 있는 같은 타입의 객체를 하나의 Set이나 Map 형태로 관리할 수 있다.
Set 멀티 바인딩
@Module class SetModule { @Provides @IntoSet fun provideHello(): String { return "Hello" } @Provides @IntoSet fun provideWorld(): String { return "World" } @Provides @ElementsIntoSet fun provideSet(): Set<String> { return HashSet(listOf("Charles", "Runa")) } } class Foo3 { var strings: Set<String>? = null @Inject set fun print() { val itr: Iterator<*> = strings!!.iterator() while (itr.hasNext()) { println(itr.next()) } } }
testMultibindingSet start Charles Runa Hello World testMultibindingSet end
- 간단히 @IntoSet 을 사용하는 것으로 Set에 객체를 추가할 수 있다.
- 여러 개를 추가하고 싶을 경우 @ElementsIntoSet Annotation을 통해 한 번에 추가할 수도 있다.Map 멀티 바인딩
- Map으로 멀티 바인딩을 구현하기 위해서 모듈 내에 @Provides 메소드에 @IntoMap을 추가해야 한다.
- Map을 사용하기 위해선 Key가 필요하기 때문에 펼도의 Key Annotation을 추가해야한다.
- Map을 위한 Key Annotation으로는 @StringKey, @ClassKey, @IntKey, @LongKey가 있다.@Component(modules = [MapModule::class]) interface MapComponent { val longsByString: Map<String?, Long?>? val stringsByClass: Map<Class<*>?, String?>? } @Module class MapModule { @IntoMap @AnimalKey(Animal.CAT) @Provides fun provideCat(): String { return "Meow" } @IntoMap @AnimalKey(Animal.DOG) @Provides fun provideDog(): String { return "Bow-wow" } @IntoMap @NumberKey(Float::class) @Provides fun provideFloatValue(): String { return "100f" } @IntoMap @NumberKey(Int::class) @Provides fun provideIntegerValue(): String { return "1" } } @Test fun testCustomMapKey() { println("testCustomMapKey start") val component: MapKeyComponent = DaggerMapKeyComponent.create() val cat = component.stringsByAnimal!![Animal.CAT] val dog = component.stringsByAnimal!![Animal.DOG] val number = component.stringsByNumber!![Float::class.java] println("cat -> $cat\ndog -> $dog\nnumber -> $number") Assert.assertEquals("Meow", cat) Assert.assertEquals("Bow-wow", dog) Assert.assertEquals("100f", number) println("testCustomMapKey end") }
testCustomMapKey start cat -> Meow dog -> Bow-wow number -> 100f testCustomMapKey end
'프로그래밍 > Android' 카테고리의 다른 글
Jetpack Compose Tutorial 영상 정리 (0) 2022.05.06 [Android] Dagger (Module, Provides, Component, Inject) 간단 용어 설명 (0) 2022.04.25 [Android] Dagger Binding의 종류 (0) 2022.04.24 [Android]Dagger Singleton과 Reusable 차이 (0) 2022.04.24 [Android] Dagger2 Component Generate 되지 않을 때 with Kotlin (0) 2022.04.24