Inject into Activity
Koject provides additional support for injecting into Activities.
Setup for Activity
The following dependency is required to take advantage of the additional support.
dependencies {
implementation("com.moriatsushi.koject:koject-android-activity:1.3.0")
}
Please also refer to the Setup document.
Basic usage
You can use the ComponentActivity.inject() or ComponentActivity.lazyInject() methods to inject any provided type.
@Provides
@Singleton
class Repository
@Provides
class Controller(
private val repository: Repository
)
class MyActivity: ComponentActivity {
val controller: Controller by lazyInject()
}
Inject Activity / Context into other types
Koject defines the @ActivityComponent and adding this annotation restricts it to be injectable only to Activity or ActivityComponent types.
@ActivityComponent
class ActivityHelper
@ActivityComponent
class ActivityHelperHolder(
val helper: ActivityHelper // can be injected
)
class MyActivity: ComponentActivity {
val helper: ActivityHelper by lazyInject() // can be injected
}
ActivityComponent types can be injected with androidx.activity.ComponentActivity and android.app.Activity.
@ActivityComponent
class ActivityHelper(
val activity: ComponentActivity // can be injected
)
Similarly, android.content.Context can be injected by adding an @ActivityContext qualifier.
@ActivityComponent
class ActivityHelper(
@ActivityContext
val context: Context // activity's context
)
Inject Activity's CoroutineScope
The ActivityComponent type can also inject an activity-scoped CoroutineScope.
The CoroutineScope requires an @ActivityCoroutineScope qualifier.
@ActivityComponent
class ActivityHelper(
@ActivityCoroutineScope
val coroutineScope: CoroutineScope // same as ComponentActivity.lifecycleScope
)
Check the Android components documentation for all available components for Android.