Skip to content

Feature request: Generate AssistedFactory for assisted injection #294

@F43nd1r

Description

@F43nd1r

Is your feature request related to a problem? Please describe.
When using assisted injection, a factory interface needs to be defined, but this interface is only boilerplate and should be possible to generate.

Describe the solution you'd like
A new annotation is introduced which generates an @AssistedFactory interface based on a constructor.
E.g.

@AutoAssistedFactory
class Example @AssistedInject constructor(@Assisted a: A, b: B, @Assisted c: C)

generates

@AssistedFactory interface ExampleFactory {
    fun create(a: A, c: C): Example
}

Alternatives
Could also make sense to put the annotation on the constructor instead of the class.

Additional context
We're using assisted injection mainly with jetpack compose ViewModel injection, where the factory needs to be specified in the @HiltViewModel annotation.

Would be nice to make sure any solution works with that, e.g.

@HiltViewModel(assistedFactory = ExampleViewModelFactory::class)
@AutoAssistedFactory
class ExampleViewModel @AssistedInject constructor(@Assisted a: A, b: B, @Assisted c: C) : ViewModel()

Generated:

@AssistedFactory interface ExampleViewModelFactory {
    fun create(a: A, c: C): ExampleViewModel
}

An optional additional function could be generated to reduce the code necessary to use the factory with compose hiltViewModel

fun exampleViewModel(
    a: A, 
    c: C,
    viewModelStoreOwner: ViewModelStoreOwner = checkNotNull(LocalViewModelStoreOwner.current) {
        "No ViewModelStoreOwner was provided via LocalViewModelStoreOwner"
    },
    key: String? = null,
): ExampleViewModel = hiltViewModel<ExampleViewModel, ExampleViewModelFactory>(viewModelStoreOwner, key) { it.create(a, c) }

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions