Skip to main content

Inject into Composable

Koject allows injection into Composable functions.

Setup for Compose

To use Koject for injection into Composable functions, you need to add the following dependencies to your project:

dependencies {
implementation("com.moriatsushi.koject:koject-compose-core:1.3.0")
}

Please also refer to the Setup document.

Using Koject with Compose

To inject a provided type into a Composable function, you can use the rememberInject() Composable function.

@Provides
class SampleController
@Composable
fun Sample(
controller: SampleController = rememberInject()
) {
/* ... */
}
tip

While you can call rememberInject() inside Composable functions, it is recommended to use it as a default argument instead. This makes it easier to replace the injected dependency during testing.

@Composable
fun Sample() {
val controller: SampleController = rememberInject() // Not recommended
}
caution

Do not call the inject() function directly from Composable functions. Creating a new instance for each render or running the injection process many times can cause performance degradation.

@Composable
fun Sample(
controller: SampleController = inject() // DO NOT!!
) {
/* ... */
}

Inject Compsable CoroutineScope

Koject defines the @ComposeComponent, which restricts a type to be injectable only into Composable functions or ComposeComponent types.

@ComposeComponent
class ComposeHelper
@ComposeComponent
class ComposeHelperHolder(
val helper: ComposeHelper // can be injected
)
val MyActivity: ComponentActivity {
val helper: ComposeHelper by lazyInject() // can be injected
}

The ComposeComponent type can also inject an comopsition-scoped CoroutineScope. The CoroutineScope requires an @ComposeCoroutineScope qualifier.

@ComposeComponent
class ComposeHelper(
@ComposeCoroutineScope
val coroutineScope: CoroutineScope // same as rememberCoroutineScope()
)

This CoroutineScope will be canceled when hidden, just like rememberCoroutineScope().

Inject Context (Android)

Similarly, android.content.Context can be injected by adding a @ComposeContext qualifier in Android.

@ComposeContext
class ComposeHelper(
@ComposeContext
val context: Context // same as LocalContext.current
)
LINK

Check the Android components documentation for all available components for Android.