I want to share a few Integer values from one fragment to the other. I don't want lose the data when the device changes configuration.
So the two ways that I came across and want to know which one will be better for my use case are:
1. Sharing a ViewModel
among multiple fragments
class SharedViewModel : ViewModel(){
...
}
class FragmentA : Fragment(){
private val model: SharedViewModel by activityViewModels()
...
}
class FragmentB : Fragment(){
private val model: SharedViewModel by activityViewModels()
...
}
2. Using combination of SafeArgs and custom ViewModelProvider.Factory
Using SafeArgs to pass data as a parameter to a navigation action from a fragment (say A) to another fragmet (say B). Implementing ViewModel
(parameterized) and ViewModelFactory
classes for fragment B. Passing the data from SafeArgs to ViewModelFactory to create a ViewModel (using ViewModelProvider
)
Something like this:
class B : Fragment() {
//Seperate classes for ViewModelB & ViewModelFactoryB
private lateinit var viewModel: ViewModelB
private lateinit var viewModelFactory: ViewModelFactoryB
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val binding: BFragmentBinding = DataBindingUtil.inflate(
inflater,
R.layout.b_fragment,
container,
false
)
viewModelFactory = ViewModelFactoryB(BFragmentArgs.fromBundle(requireArguments()).data)
viewModel = ViewModelProvider(this, viewModelFactoryB).get(ViewModelB::class.java)
return binding.root
}
}