Skip to content

Hilt ‐ Scoping with @ActivityComponent annotation and @ActivityScoped provider

Devrath edited this page Oct 9, 2023 · 2 revisions

Observation

  • Observe this is Activity scoped so when activity is destroyed and recreated the Instance is also destroyed and recreated.
  • Once created unless activity is destroyed, The address of instance remains same.

Output

// When activity is loaded for the first time 
DownloaderService class is built
// Click on the Button to call the injected reference in activity for the first time
Reference address:-> 204776435
// Click on the Button to call the injected reference in activity for the second time
Reference address:-> 204776435
// When you rotate the screen 
DownloaderService class is built
// Click on the Button to call the injected reference in activity for the third time
Reference address:-> 65550570

Implementations

DownloaderService.kt

class DownloaderService @Inject constructor(){

    init {
        PrintUtils.printLog("DownloaderService class is built")
    }

    fun downloadData(data : String) {
        PrintUtils.printLog("Reference address:-> $data")
    }

}

Modules

HiltActivityScopingModule.kt

@InstallIn(ActivityComponent::class)
@Module
object HiltActivityScopingModule {
    @ActivityScoped
    @Provides
    fun providesDownloader() : DownloaderService {
        return DownloaderService()
    }
}

Activity

MyActivity.kt

@AndroidEntryPoint
class MyActivity : AppCompatActivity() {

    private lateinit var binding: ActivityHiltScopingBinding

    @Inject lateinit var downloaderService : DownloaderService

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityHiltScopingBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setOnClickListeners();
    }

    private fun setOnClickListeners() {
        binding.apply {
            actScopedWithActivityAnnotationId.setOnClickListener {
                val code = downloaderService.hashCode().toString()
                downloaderService.downloadData(code)
            }
        }
    }
}
Clone this wiki locally