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

Time:07-22

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.

CodePudding user response:

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 enter image description here

  • Related