Udit003
12/30/2018, 7:41 AMreplaces
Fragments. I have created global instances of fragments in the activity (in order not to re-instantiate the fragments again on tab change).
Now once a fragment is loaded and replaced (on tab change),its complete lifecycle is called (from onAttach()
to onDestroy()
and onDetach()
). So I expected the viewmodel of the fragment to also get destroyed and onCleared()
called once the onDestroy()
of the fragment is called. Also new viewmodel should be instantiated when fragments is created again.
But it is not happening as expected. The viewmodel is only created once and onCleared()
is only called the first time onDestroy()
of the fragment is called. I tested it using the following code :
class HomeViewModel : ViewModel() {
init {
Log.d("Fragment_Checker","Viewmodel_INIT")
}
private var counter = 1
fun getCounter():Int{
counter++
return counter
}
override fun onCleared() {
Log.d("Fragment_Checker","ViewModel_Destroyed")
super.onCleared()
}
}
/*Fragment class */
class HomeFragment : androidx.fragment.app.Fragment() {
val viewModel: HomeViewModel by viewModel()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d("Fragment_Checker","onCreate")
}
override fun onResume() {
super.onResume()
Log.d("Fragment_Checker","Counter "+viewModel.getCounter())
}
override fun onDetach() {
super.onDetach()
Log.d("Fragment_Checker","onDetach")
}
override fun onDestroy() {
super.onDestroy()
Log.d("Fragment_Checker","onDestroy")
}
The log output looks like :
onCreate
Viewmodel_INIT
Counter 2
//tab changed
ViewModel_Destroyed
onDestroy
onDetach
//move back to home tab
onCreate
Counter 3
//tab changed
onDestroy
onDetachNail Khafizov
12/30/2018, 7:51 AMonCleared
will be called after onDestroy
in activity
https://developer.android.com/topic/libraries/architecture/viewmodel#lifecycleUdit003
12/30/2018, 7:58 AMUdit003
12/30/2018, 8:06 AMOya Canli
12/30/2018, 3:32 PMUdit003
12/31/2018, 6:01 AMUdit003
12/31/2018, 6:03 AMonCleared()
is called only the first time I switch the tabs, never thereafter.Udit003
12/31/2018, 6:04 AMonCreate()
and onDestroy()
are called everytime tab is switched.Oya Canli
12/31/2018, 7:32 AMUdit003
12/31/2018, 8:18 AM