How to pass data between fragments using a shared ViewModel in Kotlin

--

One way to pass values between fragments using a ViewModel is to have a shared ViewModel between the fragments. The ViewModel can be used to store and share data between fragments.

Here’s an example:

  1. Create a ViewModel class that will be shared between fragments:
class SharedViewModel : ViewModel() {
private val _data = MutableLiveData<String>()
val data: LiveData<String>
get() = _data

fun setData(value: String) {
_data.value = value
}
}

2. In the parent fragment, get an instance of the SharedViewModel and set the value:

class ParentFragment : Fragment() {

...

private lateinit var sharedViewModel: SharedViewModel

...

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

// Get an instance of the SharedViewModel
sharedViewModel = ViewModelProviders.of(requireActivity()).get(SharedViewModel::class.java)

// Set the value in the SharedViewModel
sharedViewModel.setData(value)
}

...
}

3. In the target fragment, get an instance of the SharedViewModel and observe the value:

class TargetFragment : Fragment() {

...

private lateinit var sharedViewModel: SharedViewModel

...

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

// Get an instance of the SharedViewModel
sharedViewModel = ViewModelProviders.of(requireActivity()).get(SharedViewModel::class.java)

// Observe the value in the SharedViewModel
sharedViewModel.data.observe(this, Observer { value ->
// Update the UI with the value
})
}

...
}

With this approach, the SharedViewModel serves as a central repository of data that both fragments can access. The parent fragment sets the value in the SharedViewModel, and the target fragment observes the value in the SharedViewModel and updates its UI accordingly.

--

--

Kashif Ahmad Sr.Android Developer @techeasesol.com
Kashif Ahmad Sr.Android Developer @techeasesol.com

Written by Kashif Ahmad Sr.Android Developer @techeasesol.com

Sr. Android Developer(Kotlin || Java || Flutter)| Co-Founder techeasesol.com || Semantic Digitisation Expert

No responses yet