Closed flamyoad closed 3 years ago
Intent passed to the activity can survive process death. The value passed before process death can still be retrieved in onRestoreInstanceState()
.
SavedStateHandle
only works with LiveData
. Feels hacky to use LiveData.asFlow()
onCreate()
is called before onRestoreInstanceState()
:)
The solution used here is by checking whether the first MutableStateFlow
in the ViewModel
has its default value set. If it has default value, it either means the activity is initialized for first time, or it has undergone process death. It also helps that MutableStateFlow
is distinctByDefault
so we can just set the same value to the MutableStateFlow
however many times we want in onResume()
callback. It won't trigger the initialization code
Checking if (savedInstanceState == null)
to safeguard against screen rotation is a bad idea because savedInstanceState
can survive process death.
// This will mean your fragment will never be recreated after process death, and when user goes back to your app // through the Recents Apps screen
if (savedInstanceState == null) {
val frameFragment = VerticalScrollingReaderFragment.newInstance()
supportFragmentManager.beginTransaction()
.replace(R.id.container, frameFragment, VerticalScrollingReaderFragment.TAG)
.commit()
}
Maybe try out Navigation Components
someday
Either by using
SaveStateHandle
or move initialization code toonResume
callback.Note that
onResume
can and will be called every time the screen is rotated. So be sure to not to call initialization code more than once.