Can I get context inside a viewmodel without recei...
# compose
p
Can I get context inside a viewmodel without receiving it as a parameter? for example, getting it from Application class? how to do it?
not kotlin but kotlin colored 1
r
usually if you really need it you'd inject it via DI and make sure it's an app context. Otherwise you'd not and just make the view model depend on use cases.
p
how to do it? the only samples I found at google are for passing parameters that can be obtained from application class:
Copy code
companion object {
    val factory : ViewModelProvider.Factory = viewModelFactory {
        initializer {
            FlightsScreenViewModel(
                FlightSearchApplication().container.flightRepository,
                FlightSearchApplication().container.userPreferencesRepository
            )
        }
    }
}
how to modify that to get a context as a parameter?
r
Yes, and the application class has its app context and typically a reference to the di component
check Hilt documentation on how params are passed, hilt has its code generation for VM factories
p
no thanks I don't wanna add Hilt to this project
just wanna make VIewModel to be able to receive a Context parameter using a viewmodel factory, but can't find how to do it on the documentation! what the fuck
can you help me?
r
FlightSearchApplication().applicationContext? or just subclass AndroidViewModel
p
Well maybe its easy for you but I'm stuck here trying to do that all the morning. Maybe can you give me a modification in that sample I posted previously to receive a context as a parameter?
r
I dont know what your FlightSearchApplication() is because you are instantiating it multiple times. bit generally it should be straighforward anywhere in your android app to get a reference of your application, and then just pass it to the factory. you are starting from some activity, so in activity you can simply retrieve the application reference. either way, this is not compose nor kotlin related, and this is something ChatGPT is good at solving