[英]Is there a way for my viewmodel to listen to events from the view when using the mvvm pattern specified by the android architecture component?
I'm getting started to use the mvvm pattern to structure my android application , and I want to maintain its pattern by letting the view to observe data from the viewmodel but in cases where there is need to only observe data when needed or once(such as navigating to a new layout), I find it difficulty to implement this case. 我开始使用mvvm模式来构建我的android应用程序 ,并且我希望通过让视图观察来自viewmodel的数据来维护其模式,但是在需要时或仅需要观察数据的情况下(例如当导航到新布局时,我发现实现这种情况很困难。 Please is it possible? 请问有可能吗? and how exactly can it be done through code( kotlin )?. 以及如何通过代码( kotlin )完成它?
I think that it's bad decision, cause your ViewModel shouldn't know anything about the View and everything from ViewModel should 'push' to View using DataBinding or Observer-Pattern. 我认为这是一个糟糕的决定,因为你的ViewModel不应该对View有任何了解,ViewModel应该使用DataBinding或Observer-Pattern “推送”到View。
The ViewModel is responsible for wrapping the model and preparing observable data needed by the view. ViewModel负责包装模型并准备视图所需的可观察数据。 It also provides hooks for the view to pass events to the model. 它还为视图提供了将事件传递给模型的钩子。 The ViewModel is not tied to the view however. 但是,ViewModel与视图无关。
Even if you decided to do such things, then you have to understand that it can be difficult to manage subscriptions when view is destroyed. 即使您决定执行此类操作,您也必须了解在销毁视图时管理订阅可能很困难。
When you wanna observe something only once, then you have to write your own extensions for LiveData ( here you can find example). 如果您只想观察一次,那么您必须为LiveData编写自己的扩展( 这里可以找到示例)。 Also you can read this article to make sure how to deal with single-events. 你也可以阅读该文章,以确保该如何处理单一事件。
If you just ask how to call something from ViewModel, when some concrete event occurs in your View, then the best solution here will be simple call method in ViewModel from your view in listener of widget(button etc) 如果您只是询问如何从ViewModel调用某些东西,当您的View中出现一些具体事件时,那么这里的最佳解决方案将是ViewModel中的简单调用方法,从您在窗口小部件的监听器(按钮等)中查看
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.