Show Dialog from ViewModel in Android MVVM Architecture

倖福魔咒の 提交于 2019-11-27 11:48:21

问题


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?


回答1:


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: https://medium.com/google-developers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150



来源:https://stackoverflow.com/questions/44146081/show-dialog-from-viewmodel-in-android-mvvm-architecture

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!