We invite future students on the course "Android Developer. Professional" to visit the open lesson on the topic "Writing a Gradle Plugin"
We also share the translation of a useful article.
An easy way to use dependency injection in Android apps
Hilt is a new dependency injection library built on top of Dagger . It allows you to use Dagger's capabilities in Android applications in a simplified way. This tutorial describes the basic functionality of the library and provides some code snippets to help you get started using Hilt in your projects.
Setting up Hilt
To set up Hilt in your application, first follow the instructions from the tutorial: Installing Gradle Build .
, Hilt, Application @HiltAndroidApp.
, Hilt .
, , , :
, , .
, .
: .
Hilt , Hilt . .
Hilt.
@Inject
@Binds
@Provides
โฎ @Inject
@Inject
, .
โฎ
Hilt .
Hilt ยซยป, Hilt, , , โ , .
, . , -.
Hilt, @InstallIn
. .
1: @Binds,
OatMilk, Milk, @Binds
. , , OatMilk . @Inject
.
2: - @Provides
, . โ -, .
, ConnectivityManager, .
Context , @ApplicationContext
@ActivityContext
.
, Hilt .
โฎ
@Inject
, Hilt , .
โฎ
, @AndroidEntryPoint
( ), , @Inject
.
, @Inject
, . lateinit, , null
.
, , , Activity
. .
, , , ? , , , . , Android, Hilt.
โฎ Android
Activity
Fragment
View
Service
BroadcastReceiver
, @AndroidEntryPoint
.
โฎ
Android, , Dagger, Android, Hilt, Hilt . .
ViewModel
ViewModel โ : , , Android. ViewModel
@ViewModelInject
, Hilt , by viewModels()
. , @Inject
.
, ViewModel
, SavedStateHandle , @Assisted
.
@ViewModelInject
, . . : Hilt Jetpack.
Hilt, @InstallIn
(<>). . , @InstallIn
(ServiceComponent.class
) , , .
, , . โฆ
. , , Milk, OatMilk. @ActivityScoped
, ActivityComponent
.
, , Hilt OatMilk . , OatMilk โ onCreate()
onDestroy()
.
milk, moreMilk OatMilk. , LatteActivity, OatMilk.
, , , , OatMilk:
, . , @ActivityScoped
, , ActivityComponent
.
: Milk, Fridge LatteActivity, , onCreate()
LatteActivity, โ onDestroy()
. , Milk ยซยป , onDestroy()
. , @ActivityRetainedScope
.
, , , , , : Hilt.
. , , - , , -. dagger.Provider.
, . , , Provider<โฆ>
, .
( Dagger Guice) , . Hilt, , Dagger , , .
Hilt , , , -, .
"Android Developer. Professional"
OTUS . . - . - :