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

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.