欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android MVVM架构

程序员文章站 2022-07-02 10:02:37
...

MVVM(Model-View-ViewModel)设计架构旨在将图形用户界面与业务逻辑的开发分离开来,核心思想为数据驱动视图

Android MVVM架构

 

  • Model

    与MVP基本相同,Model表示应用程序的数据访问层,包括本地数据库或远程服务器等,一般情况下ViewModel会持有Model

  • ViewModel

    ViewModel类似于MVP中的Presenter,负责处理程序的业务逻辑或者数据逻辑。但与之不同的是ViewModel不会持有View的引用,通过订阅-发布机制通知View更新UI

    该层的一个重要实现策略是将其与View分离,即ViewModel不应该意识到与之交互的View

  • View

    View把UI事件传递到ViewModel,ViewModel做出具体业务逻辑处理并更新数据

    View通过订阅ViewModel中的数据,在数据变更时更新UI

    View层尽可能的下沉非UI相关代码到ViewModel

 

ViewModel

ViewModel是Android Architecture Components中的一员,是Android中对MVVM架构中ViewModel的实现

源码

public abstract class ViewModel {
    /**
     * This method will be called when this ViewModel is no longer used and will be destroyed.
     * <p>
     * It is useful when ViewModel observes some data and you need to clear this subscription to
     * prevent a leak of this ViewModel.
     */
    @SuppressWarnings("WeakerAccess")   
    protected void onCleared() {
    }
}

构造ViewModel

1.无参构造

public class TestFragment extends Fragment {

    TestViewModel testViewModel;
    ……

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        testViewModel = ViewModelProviders.of(this).get(TestViewModel.class);
    }

    ……

}

 

2.有参构造

 

 

public class ViewModelFactory extends ViewModelProvider.NewInstanceFactory {
    private static ViewModelFactory factory;

    public static ViewModelFactory getInstance() {
        if (factory == null) {
            factory = new ViewModelFactory();
        }
        return factory;
    }
    /**
     * Model层,包括本地数据库和远程服务器
     * DataBase、HTTPClient 为伪代码
     */
    private final DataBase db;
    private final HttpClient httpClient;

    public ViewModelFactory() {
        db = new DataBase();
        httpClient = new HttpClient();
    }
    
    @NonNull
    @Override
    public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {

        //通过传入的Class对象判断构造的ViewModel实例
        if (AViewModel.class.isAssignableFrom(modelClass)) {
            return (T) new AViewModel(db); ;
        } else if (BViewModel.class.isAssignableFrom(modelClass)) {
            return (T) new BViewModel(httpClient); ;
        } else if (CViewModel.class.isAssignableFrom(modelClass)) {
            return (T) new CViewModel(db, httpClient); ;
        }

        //……

        return super.create(modelClass);
    }
}
public class TestFragment extends Fragment {

    TestViewModel testViewModel;
    ……

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        testViewModel = ViewModelProviders
                        .of(this, ViewMoedlFactory.getInstance())
                        .get(TestViewModel.class);
    }

    ……

}

ViewModel生命周期

ViewMoedl会在配置变更(如屏幕旋转)时保持存活

Android MVVM架构