Skip to content

Instantly share code, notes, and snippets.

@manuelvicnt
Last active June 22, 2022 12:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save manuelvicnt/5e206407f10e2ec8ed19a571a85ca28a to your computer and use it in GitHub Desktop.
Save manuelvicnt/5e206407f10e2ec8ed19a571a85ca28a to your computer and use it in GitHub Desktop.
Hilt and AssistedInject working together in Hilt v2.28-alpha times
// IMPORTANT! READ THIS FIRST
// Assisted Injection doesn't work with @HiltViewModel or @ViewModelInject
// Read more about the issue here: https://github.com/google/dagger/issues/2287
//
//
// AssistedInject and Hilt working together in v2.28-alpha times
// Example of a Assisted Presenter injected in a Fragment by Hilt
// For a solution with ViewModels, check out https://gist.github.com/manuelvicnt/437668cda3a891d347e134b1de29aee1
class MyPresenter @AssistedInject constructor(
... // Other dependencies injected by Hilt
// com.squareup.inject.assisted.Assisted annotation
@Assisted private val assistedId: String
) {
...
@AssistedInject.Factory
interface Factory {
fun create(assistedId: String): MyPresenter
}
}
// AssistedInject puts all assisted bindings in the same module.
// We need to make a decision about where to install it.
// In this case, as we only need it in fragments, we install it there.
@InstallIn(FragmentComponent::class)
@AssistedModule
@Module(includes = [AssistedInject_AssistedInjectModule::class])
// Needed until AssistedInject is incorporated into Dagger
interface AssistedInjectModule {}
@AndroidEntryPoint // Fragment injected by Hilt
class MyFragment : Fragment() {
// Inject the factory generated by AssistedInject
@Inject lateinit var presenterFactory: MyPresenter.Factory
private lateinit var presenter: MyPresenter
override fun onCreateView(...): View? {
...
// Create the ViewModel with fragment args using the factory
presenter = presenterFactory.create(args.assistedId)
}
}
// To disable checking for the InstallIn annotation in some modules,
// you need to enable the compiler option in your build.gradle file like this:
android {
defaultConfig {
javaCompileOptions {
annotationProcessorOptions {
arguments["dagger.hilt.disableModulesHaveInstallInCheck"] = "true"
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment