-
Notifications
You must be signed in to change notification settings - Fork 0
Dagger β Creating applicationβwide singleton
Devrath edited this page Oct 8, 2023
·
6 revisions
Contents |
---|
Observations |
Output |
Code |
- Application-wide singletons are needed to preserve the instance of an object during the entire lifetime of an application.
- The lifetime of the application involves the duration between the application creation and application destruction.
- Using this we can create a singleton that survives the application rotation, Meaning when the activity is destroyed and recreated.
- In the output you can observe that the memory address remains the same even on activity destruction and recreation.
// When the application is loaded for the first time and we request the object
164523186
// When the request the object for the second time again
164523186
// When the application rotates and then we request the object
164523186
Connection.kt
interface Connection {
fun connect(endpoint:String)
}
HttpsConnection.kt
class HttpsConnection @Inject constructor(): Connection {
override fun connect(endpoint: String) {
PrintUtils.printLog("HttpsConnection made")
}
}
ApplicationScope.kt
@Scope
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class ApplicationScope
HttpsConnectionModule.kt
@Module
@DisableInstallInCheck
class HttpsConnectionModule {
@ApplicationScope
@Provides
fun provideHttpsConnection() : Connection {
return HttpsConnection()
}
}
ConnectionComponent.kt
@ApplicationScope
@Component(modules = [HttpsConnectionModule::class])
interface ConnectionComponent {
fun provideHttpsConnection() : HttpsConnection
}
DiApplication.kt
@HiltAndroidApp
class DiApplication : Application() {
private lateinit var connComp : ConnectionComponent
override fun onCreate() {
super.onCreate()
connComp = DaggerConnectionComponent.builder().build()
}
fun provideHttpConnection(): ConnectionComponent { return connComp }
}
MyActivity.kt
class MyActivity : AppCompatActivity() {
private lateinit var binding: ActivityApplicationScopeBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityApplicationScopeBinding.inflate(layoutInflater)
setContentView(binding.root)
setOnClickListener()
}
private fun setOnClickListener() {
binding.apply {
initiateId.setOnClickListener {
val connComp1 = (application as DiApplication).provideHttpConnection()
PrintUtils.printLog(connComp1.hashCode().toString())
}
}
}
}