Skip to content

Instantly share code, notes, and snippets.

@mitchtabian
Last active July 3, 2020 19:20
Show Gist options
  • Save mitchtabian/7cdf070b5a0575aed4970fb3258f25e9 to your computer and use it in GitHub Desktop.
Save mitchtabian/7cdf070b5a0575aed4970fb3258f25e9 to your computer and use it in GitHub Desktop.
Basics #3: Scopes and the "tier-like" system
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.Fragment
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.scopes.ActivityScoped
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject
lateinit var someClass: SomeClass
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
println(someClass.doAThing())
}
}
@AndroidEntryPoint
class MyFragment: Fragment(){
@Inject
lateinit var someClass: SomeClass
}
@ActivityScoped
// @FragmentScoped // Try this is will throw compile time error
class SomeClass
@Inject
constructor(
){
fun doAThing(): String{
return "Look I did a thing!"
}
}

https://developer.android.com/training/dependency-injection/hilt-android#component-scopes Most important point to understand here is the "tier-like" system of scoping.

  1. @Singleton
  • Can inject into anything
  1. ActivityRetainedScope
  • Inject into everything except Singleton scoped objects
  • Ex: Can't inject into Application class
  1. ActivityScope
  • Inject into everything except Singletonand ActivityRetainedComponent scoped objects
  • Ex: Can't inject into Application or ViewModel
  1. FragmentScope
  • Inject into everything except Singleton, ActivityRetainedComponent andActivityScope` scoped objects
  • Ex: Can't inject into Activity, ViewModel or Application
  1. I think you get the idea. See the doc link: https://developer.android.com/training/dependency-injection/hilt-android#component-scopes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment