Use a SharedViewModel proposed at the official ViewModel documentation
First implement fragment-ktx to instantiate your viewmodel more easily
dependencies {
implementation "androidx.fragment:fragment-ktx:1.2.2"
}
Then, you just need to put inside the viewmodel the data you will be sharing with the other fragment
class SharedViewModel : ViewModel() {
val selected = MutableLiveData<Item>()
fun select(item: Item) {
selected.value = item
}
}
Then, to finish up, just instantiate your viewModel in each fragment, and set the value of selected from the fragment you want to set the data
Fragment A
class MasterFragment : Fragment() {
private val model: SharedViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
itemSelector.setOnClickListener { item ->
model.select(item)
}
}
}
And then, just listen for this value at your Fragment destination
Fragment B
class DetailFragment : Fragment() {
private val model: SharedViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
model.selected.observe(viewLifecycleOwner, Observer<Item> { item ->
// Update the UI
})
}
}
This answer can help you, https://stackoverflow.com/a/60696777/6761436