Skip to content

Hilt ‐ Scoping with just @Inject and without scoping components

Devrath edited this page Oct 9, 2023 · 1 revision

Observation

  • Observe that once the class is injected the reference remains the same even if its accessed multiple times.
  • If you destroy an activity and recreate it, Notice the Instance of the class is instantiated again and also the address of the injected object changes

Output

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

Implementations

ImageProcessingService.kt

class ImageProcessingService @Inject constructor() {
    fun processImage(data : String) {
        PrintUtils.printLog(data)
    }
}

Activity

MyActivity.kt

@AndroidEntryPoint
class HiltScopingActivity : AppCompatActivity() {

    private lateinit var binding: ActivityHiltScopingBinding

    @Inject lateinit var imageProcessingService : ImageProcessingService

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

    private fun setOnClickListeners() {
        binding.apply {
            notASingleTonId.setOnClickListener {
                // Not a singleton
                val code = imageProcessingService.hashCode().toString()
                imageProcessingService.processImage(code)
            }
        }
    }
}
Clone this wiki locally