Dependency Injection (Android): Implementation with Examples (Hilt) [PART 3]
Examples
If get to know something new by reading my articles, don't forget to endorse me on LinkedIn
Before you get started with the examples, check out PART 1 and PART 2
Install Hilt on Application
Add dependencies
Annotate
YouApplicationClass
with@HiltAndroidApp
Code:
@HiltAndroidApp
MyApplication : Application()
To Provide Dependency to Activity
/Fragment
To
@Inject
any object toActivity
orFragment
, we need to annotateActivity
orFragment
with@AnroidEntryPoint
Code:
@AndroidEntryPoint
SampleActivity : BaseActivity(){
@Inject
lateinit var somethingObject : SomethingObject
}
To Provide Dependency to ViewModel
To
@Inject
any object toViewModel
, we need to annotateViewModel
with@HiltViewModel
and@Inject
the constructor.Code:
@HiltViewModel
SomethingViewModel @Inject constructor() : BaseViewModel(){
@Inject
lateinit var somethingObject : SomethingObject
}
ViewModel
Constructor Injection
To
@Inject
objects toViewModel
, we need to annotateViewModel
with@HiltViewModel
and@Inject
the constructor.Code:
@HiltViewModel
SomethingViewModel @Inject constructor
(private val somethingObject : SomethingObject)
: BaseViewModel(){...}
Provide Foreground Activity Context
to any Injectable Class
To provide
ActivityContext
to any Injectable Class,@Inject
class constructor and annotate context with@ActivityContext
and register inActivityComponent
module to provide theContext
.Code:
// Lets see how to inject a custom dialog object to an activity or fragment
// First, create a CustomDialog class and inject the constructor with Context object
class CustomDialog @Inject constructor(@ActivityContext private val context : Context){....}
// Second, Register the CustomDialog to any ActivityComponent module
@Module
@InstallIn(ActivityComponent::class)
object ActivityModule{
@Provide
fun provideCustomDialog(@ActivityContext context : Context) : CustomDialog = CustomDialog(context)
}
// Third, Inject the CustomDialog to any activity or fragment
@AndroidEntryPoint
class Activity/Fragment : BaseActivity/BaseFragment{
@Inject
lateinit var customDialog : CustomDialog
}
How to Inject Interface
or Abstract Class
To provide an instance of
Interface
orAbstract Class
to any dependent object, we can't directly inject any interface or abstract class becuase there is no way to initialize interface or abstract class. So, we have to provide anImplementation
of the interface or abstract class.Code:
// Define an interface
interface SomethingObject{
fun doSomething()
}
// Define the implementation
class SomethingObjectImpl @Inject constructor() : SomethingObject{
@override
fun doSomething(){...}
}
// Register the SomeObject to any *Component module
@Module
@InstallIn(SingletonComponent/ActivityComponent/ViewModelComponent::class)
object SomethingModule{
@Provide
fun provideSomethingObject() : SomethingObject = SomethingObjectImpl()
}
That's it for this series. Happy Coding...