-
Notifications
You must be signed in to change notification settings - Fork 0
Dagger β When to use @provides and when to use @binds
Devrath edited this page Oct 8, 2023
·
2 revisions
Contents |
---|
Observations |
Implementations |
Components |
Example for @Module |
Example for @binds |
Pictorial representation |
- From the code written there is not much change but change exists in the generated code basically the number of lines in factory classes
- If you have just a few modules it does not matter but if you have thousands of modules the no of lines that are generated does matter
- Usually we use @binds when an interface comes into play and we are returning an interface and the implementation we pass in the parameter of the function in the module class function also here we need to note the implementation class must have a
@Inject
annotation added to it other-wise the dagger will not know how to create an object for the implementation.
Connection.kt
interface Connection {
fun connect(endpoint:String)
}
HttpConnection.kt
class HttpConnection @Inject constructor() : Connection {
override fun connect(endpoint: String) {
PrintUtils.printLog("HttpConnection made")
}
}
ConnectionComponent.kt
@Component(modules = [HttpsConnectionModule::class])
interface ConnectionComponent {
fun provideHttpsConnection() : HttpsConnection
}
@Module
@DisableInstallInCheck
class HttpConnectionModule {
@Provides
fun provideHttpConnection() : Connection {
return HttpConnection()
}
}
@Module
@DisableInstallInCheck
abstract class HttpConnectionModule {
@Binds
abstract fun provideHttpConnection(connection: HttpConnection) : Connection
}