Skip to content

Instantly share code, notes, and snippets.

@pphilipp
Last active September 25, 2021 13:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pphilipp/7bf4412270e7ca062ed8f2dd311ee08d to your computer and use it in GitHub Desktop.
Save pphilipp/7bf4412270e7ca062ed8f2dd311ee08d to your computer and use it in GitHub Desktop.
Dagger @modules and @BINDS

MainActivity

client = DaggerClientComponent.create().client()
"🟢 ${client.fetchData()}"

DI

@Component(modules = [ConnectionModule::class])
interface ClientComponent{
    fun client(): Client
}
@Module
interface ConnectionModule {
    @Binds
    fun bindConnection(networkConnection: NetworkConnection): Connection
}

Classes

interface Connection {
    fun doReq(): String
}
class NetworkConnection @Inject constructor() : Connection {

    val endpoint = if (BuildConfig.DEBUG) {
        "DEBUG/endpoint"
    } else {
        "PROD/endpoint"
    }

    override fun doReq() = endpoint
}
class Client @Inject constructor(
    private val connection: Connection
) {
    fun fetchData() = connection.doReq()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment