How to Send Data Between 2 Fragments Using a Shared ViewModel - Android Studio Tutorial

Publicado el: 07 noviembre 2018
en el canal de: Coding in Flow
72,580
1.4k

If we wanted to send data between 2 or more fragments of the same activity in the past, we had to do the communication over the underlying activity using interfaces and public methods. The modern approach is to communicate over the ViewModel of the activity instead, which leads to less complicated code and less tightly coupled classes.
For this, we have to create a ViewModel class from the Android Architecture Components Lifecycle library, where we store observable LiveData. By using the MutableLiveData subclass, we can access the setValue method with which we can update the Object that our LiveData wraps. SetValue has to be called on the UI thread (main thread). Alternatively, we can use postValue on a background thread. When we update our Livedata, it automatically notifies all active Observers and triggers their onChanged callback, where we can retrieve the new value and update the UI. In our fragments, we can observe this LiveData to get real-time updates and make changes to it.
By passing getActivity instead of "this" to the ViewModelProviders.of method, we can scope the lifecycle of this ViewModel to the activity instead of the fragment, and this way access it from multiple different fragments to share data between them, as long as their activity is alive. The best place to assign the ViewModel is in onActivityCreated, right after onCreateView, because this method guarantees that the onCreate method of the underlying activity has finished, so getActivity doesn't return null. This way we can also make sure that we set a new Observer and get an immediate update in cases where only the fragment's view, and not the whole fragment instance is destroyed, which is the case for example when a fragment is replaced/removed and added to the back stack, or when it is just detached and attached with a FragmentManager Transaction. In those cases, onDestroyView is called on the fragment, but not onDestroy or onDetach, and therefore also not onCreate, which could lead to bad UI states from missing data. By passing getViewLifecycleOwner as the LifecycleOwner to the LiveData, we can scope the LiveData to the lifecycle of the fragment's view and avoid memory leaks from adding multiple Observers.

Make sure to watch the Architecture Components Beginner Tutorial first:
   • Playlist  

Architecture Components dependencies:
https://developer.android.com/topic/l...

Example code:
https://gist.github.com/codinginflow/...

____________________
💻 Find the BEST programming tutorials on TutHub:
https://tuthub.io

⭐ Get my MVVM Caching Course now:
https://codinginflow.com/caching

❗ Subscribe to the channel:
   / codinginflo.  .

📨 Subscribe to the Coding in Flow newsletter:
https://codinginflow.com/newsletter

❓ Join our free developer community:
  / discord  

📣 Follow Coding in Flow on other sites:
Facebook:   / codinginflow  
Instagram:   / codinginflow  
TikTok:   / codinginflow  
Twitter:   / codinginflow  
Github: https://github.com/codinginflow

💰 Business requests, sponsoring, etc.: info@codinginflow.com


En esta página del sitio puede ver el video en línea How to Send Data Between 2 Fragments Using a Shared ViewModel - Android Studio Tutorial de Duración hora minuto segunda en buena calidad , que subió el usuario Coding in Flow 07 noviembre 2018, comparta el enlace con amigos y conocidos, en youtube este video ya ha sido visto 72,580 veces y le gustó 1.4 mil a los espectadores. Disfruta viendo!