Sobes.tech
Junior — Middle

What methods can be used to organize data exchange between Fragments in an application?

sobes.tech AI

Answer from AI

Data exchange between Fragments in Android can be organized in several ways:

  1. Through Activity — fragments communicate via the parent Activity. One fragment passes data to the Activity, and the Activity passes it to another fragment.

  2. Using ViewModel with LiveData — a shared ViewModel associated with the Activity allows fragments to observe data changes and exchange data reactively.

  3. Callback interfaces — a fragment defines an interface implemented by the Activity, which then passes data to another fragment through it.

  4. Shared Preferences or database — a less preferred method, but data can be stored in a common storage.

  5. EventBus (e.g., Otto, EventBus) — third-party libraries for event passing between components.

Example with ViewModel:

class SharedViewModel : ViewModel() {
    val selected = MutableLiveData<String>()
}

// In the first fragment
viewModel.selected.value = "Data to pass"

// In the second fragment
viewModel.selected.observe(viewLifecycleOwner) { data ->
    // Use the received data
}