在Android MVVM体系结构中从ViewModel显示对话框 [英] Show Dialog from ViewModel in Android MVVM Architecture

查看:1223
本文介绍了在Android MVVM体系结构中从ViewModel显示对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于带有新的体系结构组件的MVVM,我有一个问题,如果我的应用需要显示一个对话框,该对话框带有来自VM中发生的某些动作的3个选项,我该如何实现?谁负责向活动/片段"发送显示对话框的命令?

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?

推荐答案

与UI相关的操作,例如打开新活动或显示对话框,是从视图(活动或片段)而不是从ViewModel触发的. ViewModel没有对视图的引用,以防止泄漏并保持表示层处于活动状态".

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

您可以在ViewModel中将视图(活动或片段)订阅到可观察对象,以便在视图发生更改时可以从视图中启动对话框或新活动.

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.

我写了一篇关于此的文章,因为它并不简单.一个好的方法是将事件建模为状态的一部分,并使用事件包装器来执行导航之类的操作:

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

这篇关于在Android MVVM体系结构中从ViewModel显示对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆