简体   繁体   中英

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. Please is it possible? and how exactly can it be done through code( 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.

The ViewModel is responsible for wrapping the model and preparing observable data needed by the view. It also provides hooks for the view to pass events to the model. The ViewModel is not tied to the view however.

source

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM