How to prevent ViewModel recreation while using Kodein DI?

396 views Asked by At

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?

0

There are 0 answers