Skip to content

Dagger ‐ Creating application‐wide singleton

Devrath edited this page Oct 8, 2023 · 6 revisions

Observations

  • 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.

Output

// 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

Code

implementations

Connection.kt

interface Connection {
    fun connect(endpoint:String)
}

HttpsConnection.kt

class HttpsConnection @Inject constructor(): Connection {

    override fun connect(endpoint: String) {
        PrintUtils.printLog("HttpsConnection made")
    }

}

Scopes

ApplicationScope.kt

@Scope
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
annotation class ApplicationScope

Modules

HttpsConnectionModule.kt

@Module
@DisableInstallInCheck
class HttpsConnectionModule {

    @ApplicationScope
    @Provides
    fun provideHttpsConnection() : Connection {
        return HttpsConnection()
    }

}

Components

ConnectionComponent.kt

@ApplicationScope
@Component(modules = [HttpsConnectionModule::class])
interface ConnectionComponent {
    fun provideHttpsConnection() : HttpsConnection
}

Application

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 }
}

Activity

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())
            }
        }
    }
}
Clone this wiki locally