0

I tried to use Kodein DI library and used to to bind my Repo, NetworkService and viewModel like this

bind<MovieNetworkService>() with singleton {
    instance<Retrofit>().create(MovieNetworkService::class.java)
}

bind<MovieRepo>() with provider {
    MovieRepo(instance())
}
bind<MovieViewModel>() with provider {
    MovieViewModel(instance() , instance<Application>())
}

Activity :

class MainActivity : BaseActivity(), KodeinAware {

override val kodein: Kodein by Kodein.lazy {
    import(androidCoreModule(application))
    import(movieDIModule)
}

private val viewModel: MovieViewModel by kodein.instance()

I was able to use viewmodel and everything was working but I noticed that on device rotation my viewmodel state is not getting saved, or my Activity is creating a new ViewModel. I tried this with ViewModelProviders method and that worked but with Kodein DI my viewmodel is getting instantiated again on device rotation.

What am I doing wrong here?

Rahul Pawar
  • 403
  • 3
  • 13
  • As you are using a `provider`, every time you ask for the viewModel instance the creating lambda will be invoked. You could either use a singleton or an android scope https://docs.kodein.org/kodein-di/7.5/framework/android.html#_android_scopes – romainbsl May 25 '21 at 04:07
  • I tried singleton but the behavior remain same, then I tried Injecting ViewModelFactory and then creating viewmodel from it, that worked . – Rahul Pawar May 25 '21 at 07:34

0 Answers0