Show Dialog from ViewModel in Android MVVM Architecture

强颜欢笑 提交于 2019-11-28 18:45:18

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 could 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.

Edit: I wrote an article about this because it's not straightforward. A good approach is to model events as part of your state and use an Event wrapper for actions like navigation: