Last active
September 7, 2018 22:14
-
-
Save alwarren/1f080bd919aae21230a98b77548e4375 to your computer and use it in GitHub Desktop.
Android and Dagger2 Construcor Injection using Named (Kotlin)
This file contains hidden or 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
interface Greeting { | |
fun getData(): String | |
} | |
class GreetingRepository | |
@Inject | |
constructor( | |
@Named(HELLO) private val hello: Greeting, | |
@Named(GOODBYE) private val goodbye: Greeting | |
) { | |
fun getHello() = hello.getData() | |
fun getGoodbye() = goodbye.getData() | |
} | |
@Module | |
class GreetingModule { | |
@Provides | |
@Named(HELLO) | |
fun provideHello(): Greeting = Hello("Hello from Dagger2!!!") | |
@Provides | |
@Named(GOODBYE) | |
fun provideGoodbye(): Greeting = Goodbye("Goodbye from Dagger2!!!") | |
@Provides | |
fun provideGreetingRepository( | |
@Named(HELLO) hello: Greeting, | |
@Named(GOODBYE) goodbye: Greeting) = GreetingRepository(hello, goodbye) | |
} | |
class Hello(val text: String = "Hello from the model!!!"): Greeting { | |
override fun getData() = text | |
} | |
class Goodbye(val text: String = "Goodbye from the model!!!"): Greeting { | |
override fun getData() = text | |
} | |
// in the activity/fragment/etc | |
@Inject lateinit var repository: GreetingRepository | |
// Note: HELLO and GOODBYE are string constants |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment