You cannot inject dependencies into a function, which is what a @Composable is. @Composable functions don't have dependencies, but can get values returned by Hilt functions, like hiltViewModel().
If you need access to a ViewModel-scoped (or Application-scoped) singleton inside a @Composable, you can have that singleton injected into the ViewModel, and then access the ViewModel from the @Composable.
You can inject that singleton into the ViewModel by annotating the provider function for that object in the ViewModel hilt module as @ViewScoped.
You could install the provider into the SingletonComponent::class and annotate it as @Singleton, if you want a singleton for the whole app, instead of a singleton per ViewModel instance. More info here.
Hilt module file
@Module
@InstallIn(ViewModelComponent::class)
object ViewModelModule {
@ViewScoped
@Provides
fun provideMySingleton(): MySingletonClass = MySingletonClass()
}
Your ViewModel class:
@HiltViewModel
class MyViewModel
@Inject constructor(
val mySingleton: MySingletonClass
): ViewModel() {
...
}
Your @Composable function:
@Composable fun DisplayPrettyScreen() {
...
val viewModel: MyViewModel = hiltViewModel()
val singleton = viewModel.mySingleton //no need to assign it to a local variable, just for explanation purposes
}