Skip to content

Hilt ‐ Scoping without @Singletion annotation and with @SingletonComponent annotation

Devrath edited this page Oct 9, 2023 · 2 revisions

Observation

  • Here observe that, @Singleton annotation is not used on the Implementation class.
  • We have used just @InstallIn(SingletonComponent::class) for the module class that has a provides a method that does not have a @Singleton annotation
  • We can see that the class is destroyed and recreated the injected class is instantiated as seen from the address printed.

Output

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

Implementations

HiltNetworkService.kt

class HiltNetworkService {

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

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

Modules

HiltScopingApplicationModule.kt

@InstallIn(SingletonComponent::class)
@Module
object HiltScopingApplicationModule {

    @Provides
    fun getNetworkService() : HiltNetworkService {
        return HiltNetworkService()
    }

}

Activity

MyActivity.kt

@AndroidEntryPoint
class MyActivity : AppCompatActivity() {

    private lateinit var binding: ActivityHiltScopingBinding

    @Inject lateinit var hiltNetworkService : HiltNetworkService

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

    private fun setOnClickListeners() {
        binding.apply {
            singletonCompWithoutSingletonAnnotationId.setOnClickListener {
                val code = hiltNetworkService.hashCode().toString()
                hiltNetworkService.callNetworkEndPoint(code)
            }
        }
    }
}
Clone this wiki locally