首页 > 解决方案 > MVVM 架构中的导航

问题描述

在使用 MVVM 架构实现的 Android 或 iOS 项目中,正确的导航方法是什么?

  1. ViewModel 决定导航何时发生以及哪个是目的地
  2. ViewModel 决定导航何时发生,View 决定哪个是目的地
  3. 视图决定导航何时发生以及哪个是目的地

标签: androidioskotlinmvvmswiftui

解决方案


I believe it's supposed to be like so:

  1. The ViewModel decides when the navigation happens, the destination, and also the data, if any, to be passed to the destination.
  2. The View performs the actual action, decides on the navigation animation and other UI stuff.

So ultimately we need the logic to be in the ViewModel and the UI stuff should be the responsibility of the View.

One way to go about it is to fire an Event in the ViewModel when navigation needs to happen. This event should specify the destination and data to be passed if any. The View subscribes to this event and whenever it is fired, it decides upon the navigation animation and then performs the actual action (the actual act of navigation is a part of the UI) taking into consideration the destination and the data to be passed.


推荐阅读