Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create new instance of viewModel in koin every time

Am Using Koin as Dependency injection pattern in my project, I need to create new instances whenever i load fragment/activity, now am using the following pattern, Any solution for that it might save lots of time.

private val homeViewModel: HomeViewModel by viewModel()
like image 713
jins joseph Avatar asked Sep 16 '25 02:09

jins joseph


2 Answers

The question is why you want new instances everytime? The whole concept of ViewModel is to retain the same instance and data. viewModel {} creates new instance everytime you inject it unless it is not shared.

Don't know why it is not working for you, but I think you can use factory{} instead of viewModel{}.

factory{
    // this is because you need new instance everytime.
    HomeViewModel()
}
like image 121
Birju Vachhani Avatar answered Sep 18 '25 19:09

Birju Vachhani


You are going to want to forego using by viewmodel and instantiate the class directly. You can get global (scoped) variables through getKoin().get().

private val viewModel = HomeViewModel(getKoin().get())
like image 36
Isaac Paul Avatar answered Sep 18 '25 17:09

Isaac Paul