Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Android ViewModel: How to get a result from the Activity (best practice)?

I have the following situation:

  1. The user opens a dialog in which the user enters information
  2. The user closes the dialog and returns to the default UI
  3. The data is send to the backend

Now I wonder how to implement this in a good way. At first, I think the Activity calls a method in the ViewModel to trigger an event. Secondly, the ViewModel updates an LiveData-object to trigger an observer in the Activity which opens the dialog. But after that I don’t know how to implement the rest in a "best practice"-way. My current implementation is that, when the user closes the dialog, the Activity calls a "finish"-method in the ViewModel and hands over the data from the dialog as arguments. After that the ViewModel updates the LiveData-object and the event is over.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You don’t specifically need to have a flow Activity -> ViewModel -> Activity, when you’re just about opening a dialog. It would make sense if you have to get some info (for example price) from your back-end side and include it into your dialog description. If it’s just a simple UI stuff like "show-me-a-dialog", then it’s fine to leave it on your UI layer only.

And when the dialog is closed, you’ll just pass needed arguments to VM, make your back-end request, and in this case it’s logical to emit some event to your Live Data and it’s a common practice.

Android has a bunch of really great articles and they were added no so long ago, take a look here (picture was also taken from the article). They have clear and simple explanation about all UI-VM-Data/Domain communication and how to do that it in the "right way".

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading