简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM