Show Dialog from ViewModel in Android MVVM Architecture

后端 未结 3 792
隐瞒了意图╮
隐瞒了意图╮ 2020-12-13 04:24

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 ha

相关标签:
3条回答
  • 2020-12-13 04:52

    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

    0 讨论(0)
  • 2020-12-13 05:01

    In Android, most commonly the communication from the ViewModel to the view (Activity/Fragment) is through observing LiveData value. In ViewModel set MutableLiveData value and expose it to the view as LiveData to observe. This is handy when reacting to some state change. Set state persists and is relevant until the next change. It's handy for instance with configuration changes, our view state is preserved in the ViewModel.

    But sometimes this is not desirable - with "brief" or "stateless" actions - which only briefly change the state of the UI and are relevant only at the time when action happened - such as action to show a message (be it a toast or a snackbar) - we don't want to re-show an error message 10 min later just because screen rotation occurred; or a navigation action - we don't want to reopen another screen on top. These can be handled with SingleLiveEvent pattern as described in Jose Alcérreca's answer.

    I have created a small library for easy implementation for sending such actions - called "brief actions" - actions, not events, because events are something we react to and actions we send/initiate.

    You can check it out here:

    https://bintray.com/vlad-markovic/maven/com.vladmarkovic.briefactions#read

    It's also open source; please feel free to contribute:

    https://github.com/vlad-markovic/AndroidBriefActions

    Import in Gradle with:

    implementation "com.vladmarkovic.briefactions:briefactions:$briefActionsVersion"
    
    0 讨论(0)
  • 2020-12-13 05:17

    As everyone says ViewModel should not contain Context or reference to classes that contain Context. So it is not a good idea to show dialog from ViewModel. You should show dialog from view, not from viewmodel.

    0 讨论(0)
提交回复
热议问题