-
Notifications
You must be signed in to change notification settings - Fork 0
Dagger β Scoping, normal example using singleton
Devrath edited this page Oct 6, 2023
·
11 revisions
Contents |
---|
Observations |
Output |
Code |
// ----> When the Screen is first loaded
connInterface1 reference---> 226246109
connInterface1 reference---> 226246109
// ----> App Screen is rotated and
connInterface1 reference---> 8298091
connInterface1 reference---> 8298091
Contents |
---|
implementations |
Scopes |
Modules |
Components |
Activity |
Connection.kt
interface Connection {
fun connect(endpoint:String)
}
HttpConnection.kt
class HttpConnection @Inject constructor() : Connection {
override fun connect(endpoint: String) {
PrintUtils.printLog("HttpConnection made")
}
}
HttpsConnection.kt
class HttpsConnection @Inject constructor(): Connection {
override fun connect(endpoint: String) {
PrintUtils.printLog("HttpsConnection made")
}
}
NetworkLibrary.kt
class NetworkLibrary @Inject constructor( val connection: Connection) {
fun initilizeNetworkLibrary() {
connection.connect("www.client.com")
PrintUtils.printLog("Network library is initialized")
}
}
ApplicationScope.kt
@Scope
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class ApplicationScope
HttpConnectionModule.kt
@Module
@DisableInstallInCheck
class HttpConnectionModule {
@Provides
fun provideHttpConnection() : Connection { return HttpConnection() }
}
HttpConnectionModule.kt
@Module
@DisableInstallInCheck
class HttpsConnectionModule {
@ApplicationScope
@Provides
fun provideHttpsConnection() : Connection { return HttpsConnection() }
}
ConnectionComponent.kt
@ApplicationScope
@Component(modules = [HttpsConnectionModule::class])
interface ConnectionComponent {
fun inject(activity: IntroScopeDemoActivity)
fun provideHttpsConnection() : HttpsConnection
}
class IntroScopeDemoActivity : AppCompatActivity() {
@Inject lateinit var connInterface1 : Connection
@Inject lateinit var connInterface2 : Connection
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_intro_scope_demo)
val comp = DaggerConnectionComponent.builder().build()
comp.inject(this@IntroScopeDemoActivity)
PrintUtils.printLog("connInterface1 reference---> "+connInterface1.hashCode().toString())
PrintUtils.printLog("connInterface1 reference---> "+connInterface2.hashCode().toString())
}
}