androidmvvmarchitecturecomponentspresenter

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?


Solution

  • 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