在 Android MVVM 架构中显示来自 ViewModel 的对话框 [英] Show Dialog from ViewModel in Android MVVM Architecture

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

问题描述

关于具有新架构组件的 MVVM,我有一个问题,如果我的应用程序需要显示例如一个对话框,其中包含来自我的 VM 中发生的某些操作的 3 个选项,我应该如何实现?谁负责向 Activity/Fragment 发送显示对话框的命令?

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.

我写了一篇关于这个的文章,因为它并不简单.一个好的方法是将事件建模为状态的一部分,并使用事件包装器进行导航等操作:https://medium.com/google-developers/livedata-with-snackbar-navigation-and-other-events-the-singleliveevent-case-ac2622673150

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天全站免登陆