Search code examples
androidmvvmviewmodelandroid-viewmodel

How to pass data from one ViewModel to another ViewModel


I have a fragment in which I have two TextViews with hint texts. When a user clicks on the first one a bottom sheet dialog opens and shows a list of possible options. User selects an option, and the option info is displayed in the first TextView instead of hint text. When the user clicks on the second TextView the very same bottom sheet dialog opens, but shows a filtered list of options (the list is filtered based on the first choice). User selects an option and the option info is displayed in the second TextView instead of the hint text as well. I have achieved to have this by using only one ViewModel for the fragment itself, but it doesn't seem right because the ViewModel does too much. Therefore, I tried using two ViewModels: one for the fragment itself to update when the options are selected, and one for the bottom sheet dialog to load the data and show them in the list. But the issue is that I cannot share the selected option from the bottom sheet dialog ViewModel to the fragment ViewModel. Is there a way to achieve what I want to achieve by using two ViewModels?


Solution

  • For now, as far as I know, the Google recommended approach is to have a shared view model for such cases.

    I am not sure how you implemented it in your case - but if it is something similar to what Google recommends - then it is ok.

    Of course, you can create an elaborate architecture of multiple view models connected via interfaces and UI calls, but I don't know if it is worth it.

    The general rule for implementing such cases is not to use the cleanest approach with a lot of abstractions and generifications but to use the most optimal one(in terms of time spent and simplicity/readability of the code) that still tries to follow OOD principles.

    Hope it helps.