Dependency Injection

Learn how to inject code into your composables

There is no Dependency Injection (DI) framework preconfigured in Android Blaze.

This is a conscious choice, as Dependency Injection comes with the hidden costs of configuring, spreading DI code in your codebase and potentially slowing down your builds.

Dependency Injection frameworks might not cover cases where you expect dependency injection to work, such as injecting in WorkManagers, BroadcastReceivers and other part of Android.

 

How to inject dependencies in your components

All DI in Android Blaze is done by writing simple Kotlin functions that create the object you need and return it. It is really simple to create your own.

 

Here is an example of how to create a function that creates a view model:

fun homeTabViewModel(): HomeTabViewModel {
    return HomeTabViewModel(photosRepository())
}

which you can then use in your composable function using the usual viewModel {}

@Composable
fun HomeTab() {
    val homeTabViewModel = viewModel { homeTabViewModel() }

    // ... the rest of your composable function
}
 

All Android Blaze specific provided functions (such as applicationContext() or analytics()) are kept in DependencyInjection.kt

Recommended DI frameworks

If you feel the need to integrate a DI framework in your project, we recommend the following options:

  • Koin – One of the most popular choices in the Android community. A lot of documentation available.
  • Google’s Hilt – Google’s framework for Dependency Injection. Simple to setup. Covers most common scenarios such as Activities, Fragments and Composable functions.
 
Did this answer your question?
😞
😐
🤩