Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show Dialog from ViewModel in Android MVVM Architecture

About MVVM with new architecture components, I've a question, how should I implement if my app needs to display for example a Dialog with 3 options from some action that happened in my VM? Who is responsible for sending to Activity/Fragment the command to show dialog?

like image 928
lucasb.aquino Avatar asked May 23 '17 22:05

lucasb.aquino


People also ask

What is an example of MVVM in Android?

Here is an example of a single activity User-Login android application to show the implementation of the MVVM architecture pattern on projects. The application will ask the user to input the Email ID and password. Based on the inputs received the ViewModel notifies the View what to show as a toast message.

What is viewmodel (MVVM)?

Model — View — ViewModel (MVVM) is the industry-recognized software architecture pattern that overcomes all drawbacks of MVP and MVC design patterns. MVVM suggests separating the data presentation logic (Views or UI) from the core business logic part of the application. The separate code layers of MVVM are:

How to communicate from ViewModel to the view in Android?

In Android, most commonly the communication from the ViewModel to the view (Activity/Fragment) is through observing LiveData value. In ViewModel set MutableLiveData value and expose it to the view as LiveData to observe. This is handy when reacting to some state change. Set state persists and is relevant until the next change.

How to understand the MVVM architecture?

To understand the MVVM Architecture, let us learn with an example of a User Login application that is built by implementing the MVVM architecture. The application will prompt the user to enter their Email ID and password based on the received user inputs. The ViewModel will notify the View what to show to the user as a toast message.


1 Answers

UI-related actions like opening new activities or showing dialogs are triggered from the view (an activity or fragment), not from a ViewModel. The ViewModel doesn't have a reference to the view to prevent leaks and keep the presentation layer "reactive".

You can subscribe your view (activity or fragment) to an observable in the ViewModel so that when it changes, you can start your dialog or new activity from the view. Then the view resets that state in the ViewModel when it's dealt with.

Edit: We wrote official guidance for this: https://developer.android.com/topic/architecture/ui-layer/events

like image 172
Jose Alcérreca Avatar answered Oct 21 '22 13:10

Jose Alcérreca