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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

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

Write a response