0

There is a straight forward implementation for fragment to fragment communucation using viewmodel and a host activity (ViewModel by activityViewModels()). However I have a case where there is no intermediate activity for communication.

I am working on a modularized application with modules including app and wallet. app depends on wallet and the wallet module has a fragment: WalletFragment that can be accessed by the app's module MainActivity.

Now if I create a viewModel instance for app's module MainActivity, I won't be able to access it from wallet module because wallet module has no dependency on the app module. How can I achieve this?

To the main question: I have another scenerio where the WalletFragment calls a new BottomSheetFragment in the same wallet module. Is there a way I can create a ViewModel instance for this WalletFragment that can be accessed by the BottomSheetFragment without having to take the route of ViewModel by activityViewModels(). In other words is there such thing as ViewModel by fragmentViewModels()?

Urchboy
  • 725
  • 2
  • 12
  • 26

1 Answers1

0

I think you can use something called SharedViewModel, for example:

This is the viewModel that will be shared.

class ShareableViewModel(): ViewModel(){

    val message = MutableLiveData<String>()

    fun sendMessage(text: String) {
        message.value = text
    }
}

And now the FirstFragment is the fragment that will send something, in this case, just a string.

class FirstFragment: Fragment(){

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        val shareableViewModel = ViewModelProvider(requireActivity()).get(ShareableViewModel::class.java)
        shareableViewModel.sendMessage("Message from first Fragment")
    }
}

Finally, SecondFragment is the fragment that is receiving the message fragment Fragment1

class SecondFragment: Fragment(){

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

    val shareableViewModel = ViewModelProvider(requireActivity()).get(ShareableViewModel::class.java)
        shareableViewModel.message.observe(viewLifecycleOwner, Observer {
        //Receiving the message
        })
    }
}

I hope it can help. For more details, you can see:

rguzman
  • 319
  • 3
  • 8