0

I have started basic implementation of MVVM for a User selection screen. I'm not sure how best to handle selecting of a user to adhere to best practices.

LogInActivity contains UsersFragment. UsersFragment has an associated ViewModel (UsersFragmentVM). UsersFragmentVM handles the exposing of Users. The UsersFragment displays them to the user. When the user clicks on a user, what should be the flow of events?

My first thought was to have an observable in UsersFragment that LogInActivity could subscribe to and receive a User object however I'm not confident the Views should be communicating?

So I thought maybe the ViewModel should receive the event from View (user clicking), but then how does that event get to LogInActivity? A separate events ViewModel that both LogInActivity and UsersFragmentVM implement?

Similar to Sharing data between fragments using new architecture component ViewModel however that answer uses LiveData. I'm using generic MVVM with Rx to get away from Android dependency for easier testing and portability. Unless there is a general recommended way of sharing ViewModels?

Dre
  • 543
  • 1
  • 4
  • 17
  • 1
    Possible duplicate of [Sharing data between fragments using new architecture component ViewModel](https://stackoverflow.com/questions/44272914/sharing-data-between-fragments-using-new-architecture-component-viewmodel) – Samuel Eminet Oct 15 '18 at 10:26
  • That answer uses LiveData however I'm using generic MVVM with Rx to get away from Android dependency for easier testing and portability. Unless there is a general recommended way of sharing ViewModels? – Dre Oct 15 '18 at 10:40
  • as samuel comment pass to the viewmodel "parent activity " of fragments so when you set live data in certain fragment and the other if observe this live data will get it's updates . ` ViewModelProviders.of(getActivity()).get(SharedViewModel.class); model.getSelected().observe(this, { item -> // update UI });` – Zeinab Abdelmawla Oct 15 '18 at 10:44
  • you could use rxjava and handle the event – Raza Oct 15 '18 at 10:47
  • There is nothing to do with using livedata or reactive, have you read first answer? what about that link?https://developer.android.com/topic/libraries/architecture/viewmodel#sharing – Samuel Eminet Oct 15 '18 at 10:48
  • Sorry, I meant the link and the answers rely on ViewModelProviders, NOT LiveData as I mentioned which is irrelevant. From what I understand, ViewModelProviders is a common pool of ViewModels. Is there a way to do this with Rx such as putting a bunch in the Application class (seems like it would become a God scenario) – Dre Oct 15 '18 at 10:54
  • ViewModelProviders is the right way to go so your view model are tied to your view lifecycle, there ios no drawback to use it even for testing – Samuel Eminet Oct 15 '18 at 12:00
  • I'm trying to keep as least reliant as possible on Android so I can eventually make use of kotlin multiplatform projects. – Dre Oct 15 '18 at 12:13

0 Answers0