ViewModel for Fragment instead of accessing Activity ViewModel?

The problem is pretty simple. The question is about using ViewModels, LiveData, and other Lifecycle- related arch approaches.
I have activity with NavDrawer that toggles fragments inside.
And also I have a case when two fragments are present on the screen at the same time - this will be the main pain. One snippet has a ViewPager with nested ones Fragments( don't ask why ). Another fragment simply receives information from the first when the user performs some actions. This is achieved simply by sharing viewmodel activity. But the application itself has a lot of business logic, and as we move forward, the presentation model becomes more and more.
What I want to ask is not a receipt or rules, how to fix it, or maybe how to overcome it, correcting the whole structure of the project. I want to ask for advice on how I can apply the MVVM approach in the style of android.arch.lifecycle for my use case.
I have not seen anything more complicated than just splitting an Activity ViewModel between fragments. But often this is not a cure.enter image description here

, - . , ActivityViewModel. () FirstFragment , ViewPager FirstFragment ChildFragments ActivityViewModel ( ). ViewModel.
, ViewModel . Activity/Fragments/ChildFragments ViewModels. - ?
:

  • ViewModels . ViewModel / -, - . - , ?
  • (, !)
  • - DB/SharedPrefs/Realm ( :().

  • !

, , ? ? Uncle Bob superhero ?

PS - , UML - . .
PPS - Google.

+11
2

-, ViewModel .

ViewModel, , , , .

, , , ViewModel, .

, ViewModel ViewModel Fragments, God ViewModel, ViewModel.

+3

, , ViewModel .

ViewModel

, , MyActivityViewModel , . , - , ViewModel ViewModel :

ViewModelProviders.of(getActivity()).get(MyActivityViewModel.class); // Like this in fragment.

&

ViewModelProviders.of(this).get(MyActivityViewModel.class); // Like this in activity.

ViewModel .


ViewModel FirstFragment , ChildFragment:

ViewModel , FragmentViewModel FragmentViewModel :

ViewModelProviders.of(this).get(FragmentViewModel.class); // Like this in FirstFragment which is having view pager.

&

ViewModelProviders.of(getParentFragment()).get(FragmentViewModel.class); // Like this in View pager fragments, getParentFragment() is First fragment in our case.

MyActivityViewModel FirstFragment, :

ViewModelProviders.of(getActivity()).get(MyActivityViewModel.class);
0

Source: https://habr.com/ru/post/1685832/


All Articles