This used to be done using @Named
with Dagger. Now there's a new way.
Created
July 3, 2020 20:41
-
-
Save mitchtabian/2838e5497b2b2e5777d0f5c0e6ecc79e to your computer and use it in GitHub Desktop.
Basics #7: Multiple Bindings of the same type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import androidx.appcompat.app.AppCompatActivity | |
import android.os.Bundle | |
import dagger.Module | |
import dagger.Provides | |
import dagger.hilt.InstallIn | |
import dagger.hilt.android.AndroidEntryPoint | |
import dagger.hilt.android.components.ApplicationComponent | |
import javax.inject.Inject | |
import javax.inject.Qualifier | |
import javax.inject.Singleton | |
@AndroidEntryPoint | |
class MainActivity : AppCompatActivity() { | |
@Inject | |
lateinit var someClass: SomeClass | |
override fun onCreate(savedInstanceState: Bundle?) { | |
super.onCreate(savedInstanceState) | |
setContentView(R.layout.activity_main) | |
println(someClass.doAThing()) | |
} | |
} | |
class SomeClass | |
@Inject | |
constructor( | |
@Impl1 private val someInterfaceImpl1: SomeInterface, | |
@Impl2 private val someInterfaceImpl2: SomeInterface | |
){ | |
fun doAThing(): String{ | |
return "Look I got: ${someInterfaceImpl1.getAThing()} & ${someInterfaceImpl2.getAThing()}" | |
} | |
} | |
class SomeInterfaceImpl1 | |
@Inject | |
constructor(): SomeInterface { | |
override fun getAThing() : String{ | |
return "A Thing1" | |
} | |
} | |
class SomeInterfaceImpl2 | |
@Inject | |
constructor(): SomeInterface { | |
override fun getAThing() : String{ | |
return "A Thing2" | |
} | |
} | |
interface SomeInterface{ | |
fun getAThing(): String | |
} | |
@InstallIn(ApplicationComponent::class) | |
@Module | |
class MyModule{ | |
@Impl1 | |
@Singleton | |
@Provides | |
fun provideSomeInterface1(): SomeInterface{ | |
return SomeInterfaceImpl1() | |
} | |
@Impl2 | |
@Singleton | |
@Provides | |
fun provideSomeInterface2(): SomeInterface{ | |
return SomeInterfaceImpl2() | |
} | |
} | |
@Qualifier | |
@Retention(AnnotationRetention.BINARY) | |
annotation class Impl1 | |
@Qualifier | |
@Retention(AnnotationRetention.BINARY) | |
annotation class Impl2 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment