Skip to content

[AssistedInject] Integration with @HiltViewModel #2287

Closed
@manuelvicnt

Description

@manuelvicnt

It'd be nice to have Assisted Injection support for Hilt ViewModels.

A nice API would be something like the following:

@HiltViewModel
class PlantDetailViewModel @AssistedInject constructor(
    savedStateHandle: SavedStateHandle,
    plantRepository: PlantRepository,
    @Assisted private val plantId: String
) : ViewModel() { ... }
@AssistedFactory
interface PlantDetailViewModelFactory {
    fun create(plantId: String): PlantDetailViewModel
}

And use it from the View like:

@AndroidEntryPoint
class PlantDetailFragment : Fragment() {

    private val args: PlantDetailFragmentArgs by navArgs()

    @Inject
    lateinit var plantDetailViewModelFactory: PlantDetailViewModelFactory

    private val plantDetailViewModel: PlantDetailViewModel by viewModels {
        plantDetailViewModelFactory.create(args.plantId)
    }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions