Search code examples
androidmvvmandroid-livedataandroid-mvvm

What is the best way to call fragments method from ViewModel in MVVM architecture using live data


For eg, As ViewModel should be loosely coupled we cant pass interface reference to ViewModel to get a callback from Viewmodel and call the method implemented in the fragment.

Also please provide an example or reference to call with methods with two or more params using livedata.


Solution

  • Make a live data variable in ViewModel and attach an observer in Fragment to that variable and whenever there will be a change in data then the function will be automatically invoked.

    For Example:

       viewModel.loading.observe(viewLifecycleOwner, { loading ->
            loading?.let {
              // Here, I'm calling a new function named setLoaderVisibility
    
                setLoaderVisibility(loader = binding.shimmerProductDetail, binding.containerBody, isLoaderVisible = loading)
            }
        })
    

    Feel free to ask if something is unclear.