How to use android navigation without binding to UI in ViewModel (MVVM)?

后端 未结 1 810
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-08 14:39

I am using android navigation that was presented at Google I/O 2018 and it seems like I can use it by binding to some view or by using NavHost to get it from Fragme

相关标签:
1条回答
  • 2021-02-08 15:29

    How can I navigate from ViewModel?

    The answer is please don't. ViewModel is designed to store and manage UI-related data.

    New Answer

    In my previous answers, I said that we shouldn't navigate from ViewModel, and the reason is because to navigate, ViewModel must have references to Activities/Fragments, which I believe (maybe not the best, but still I believe it) is never a good idea.

    But, in recommended app architecture from Google, it mentions that we should drive UI from model. And after I think, what do they mean with this?

    So I check a sample from "android-architecture", and I found some interesting way how Google did it.

    Please check here: todo-mvvm-databinding

    As it turns out, they indeed drive UI from model. But how?

    1. They created an interface TasksNavigator that basically just a navigation interface.
    2. Then in the TasksViewModel, they have this reference to TaskNavigator so they can drive UI without having reference to Activities / Fragments directly.
    3. Finally, TasksActivity implemented TasksNavigator to provide detail on each navigation action, and then set navigator to TasksViewModel.
    0 讨论(0)
提交回复
热议问题