Android screen rotation creates new instance of fragment which causes the instance of viewmodel to be lost
See original GitHub issueDescribe the bug
I am using -
implementation "org.koin:koin-androidx-viewmodel:2.1.0-alpha-3"
In my modules, I declare it as -
private val viewModels = module { viewModel { (handle: SavedStateHandle) -> HomeViewModel(handle, get()) } }
I create my HomeFragment
inside onCreate()
of MainActivity
when savedInstanceState == null
.
In my HomeFragment
I inject my viewModel like this -
private val homeViewModel: HomeViewModel by viewModel { parametersOf( Bundle(), "homeViewModel" ) }
And in HomeFragment
, inside onViewCreated()
I observe the changes in livedata -
homeViewModel.showResults().observe(this, Observer { .... })
When the screen is rotated to landscape, the onCreate()
of MainActivity
is called again and the fragment is newly created and the viewModel instance in the fragment is gone.
Is it not possible for the viewmodel instance to be retained even after screen rotation change?
Issue Analytics
- State:
- Created 4 years ago
- Comments:10
I tried and found out two interesting things:
if you are using
val vm: MyViewModel by inject()
, the viewModel can’t survive config change.But if you use:
Now the viewModel could survive config change
I used to have this issue with a similar approach, I had a couple of fragments and a navigation drawer and each time I had a configuration change when the views are reconstructed my fragments would somehow get a new instance of their
viewmodel/s
, which didn’t seem right, considering this lifecycle diagram, but I guess this is true for activities but not fragments?What I had to do was to use tags/ids in my
supportFragmentManager
when Icommit
and upon getting navigation item change I would callsupportFragmentManager.findFragmentByTag
and do a null check on the result, if it is null I’ll create a new instance of my fragment.Additionally I also use
retainInstance
on my fragments, the difference in lifecycle handling are as follows: Complete lifecycleHope this helps you 😉