Android ViewModel+liveData+lifecycle+databinding打造MVVM

Google JetPack

最近google推出JetPack官方架构组件,最近有时间在网上看了很多类似的文章,对ViewModel和lifeCycle有了大概的了解,谷歌意在使用这些组件完成代码解耦,实现数据驱动UI的模式,但是还没有深入的了解,效率优先,还是动手才能看到这些架构组件具体是怎样的使用,来实现简单的MVVM模式。 每个组件的单独使用网上有很多文章,大家可以自行去查看,我也是拿来主义,直接上代码。

MVVM设计模式:

网络请求:

接口使用的网上一位大神测试用的接口,UI也是直接使用,本人较懒,请求使用流行的Retrofit2+rxjava2,将其封装在BaseModel中:

public class BaseModel {
    public BaseModel() {}

    public void getImage(String format, int idx, int n, BaseObserver observer) {
        ApiRepertory.getInstance().getService().getImage(format, idx, n)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
    }
}

复制代码

lifeCycle绑定页面生命周期

此处的Presenter用于将ViewModel中的业务绑定到不同的生命周期中去执行业务逻辑。

public abstract class BaseLifeCycle

implements ILifeCycle { protected Context mContext; protected P mPresenter; public BaseLifeCycle(Context context) { this.mContext = context; } protected void addPresenter(P mPresenter) { if (mPresenter != null) { this.mPresenter = mPresenter; } } @Override public void onCreate(@Nullable LifecycleOwner owner) { } @Override public void onDestroy(@Nullable LifecycleOwner owner) { } @Override public void onStart(@Nullable LifecycleOwner owner) { } @Override public void onResume(@Nullable LifecycleOwner owner) { } @Override public void onPause(@Nullable LifecycleOwner owner) { } @Override public void onStop(@Nullable LifecycleOwner owner) { } @Override public void onLifecycleChanged(@Nullable LifecycleOwner owner, @Nullable Lifecycle.Event event) { } } 复制代码

这里ILifeCycle接口用来继承LifecycleObserver,SupportActivity内部已经实现了LifecycleOwner接口用来获取lifeCycle,加入LifecycleObserver来添加观察者来响应不同的生命周期。

public interface ILifeCycle extends LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    void onCreate(@Nullable LifecycleOwner owner);

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    void onDestroy(@Nullable LifecycleOwner owner);

    @OnLifecycleEvent(Lifecycle.Event.ON_START)
    void onStart(@Nullable LifecycleOwner owner);

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    void onResume(@Nullable LifecycleOwner owner);

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    void onPause(@Nullable LifecycleOwner owner);

    @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
    void onStop(@Nullable LifecycleOwner owner);

    @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
    void onLifecycleChanged(@Nullable LifecycleOwner owner,
                            @Nullable Lifecycle.Event event);
}
复制代码

还有此处的BasePresenter用来绑定ViewModel,实现其中的业务逻辑。

public abstract class BasePresenter {
    protected M mViewModel;

    public BasePresenter(M viewModel) {
        if (viewModel != null) {
            this.mViewModel = viewModel;
        }
    }
}
复制代码

下面是将lifeCycle和databinding写入BaseActivity中比较简单,没有集成过多的其他组件。 getLifecycle().addObserver(mLifeCycle);将不同页面的生命周期逻辑绑定到不同页面中, mLifeCycle.addPresenter(mPresenter);将业务处理部分加入到生面周期中,用于在不同的生命周期中处理不同的业务。 startListenerData();此处用于实现ViewModel数据返回View进行响应刷新的逻辑。

public abstract class BaseActivity
        extends AppCompatActivity{
    protected Context mContext;
    protected L mLifeCycle;
    protected V dataBinding;
    protected P mPresenter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        dataBinding = DataBindingUtil.setContentView(this, getLayoutRes());
        initView();
        getLifecycle().addObserver(mLifeCycle);
        mLifeCycle.addPresenter(mPresenter);
        startListenerData();
    }

    protected abstract void startListenerData();

    protected abstract void initView();

    protected abstract int getLayoutRes();
}
复制代码

下面看下在Activity中的具体实现: ImageViewModel中就是具体的业务逻辑的实现与数据的绑定; MainLifeCycle是该页面的生命周期,presenter在不同的生命周期实现不同的处理。

public class MainActivity extends BaseActivity {
    private ProgressDialog mProgressDialog;
    private ImageViewModel baseViewModel;

    @Override
    protected void initView() {
        mLifeCycle = new MainLifeCycle(this);
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("加载中");
        baseViewModel = ViewModelProviders.of(this).get(ImageViewModel.class);
        dataBinding.setClick(new ClickHandler());
        //将presener绑定生命周期
        mPresenter = new ImagePresenter(baseViewModel);
        mProgressDialog.show();
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_main;
    }

    @Override
    protected void startListenerData() {
        baseViewModel.getMutableLiveData().observe(this, new Observer>() {
            @Override
            public void onChanged(@Nullable Data imagesBeanData) {
                if (imagesBeanData.getErrorMsg() != null) {
                    Toast.makeText(mContext, imagesBeanData.getErrorMsg(), Toast.LENGTH_SHORT).show();
                    mProgressDialog.dismiss();
                    return;
                }
                dataBinding.setImageBean(imagesBeanData.getData());
                setTitle(imagesBeanData.getData().getCopyright());
                mProgressDialog.dismiss();
            }
        });
    }
    
    public class MainLifeCycle extends BaseLifeCycle {
    public MainLifeCycle(Context context) {
        super(context);
    }

    @Override
    public void onStart(@Nullable LifecycleOwner owner) {
        Log.e("MainActivity", "onCreate");
        mPresenter.loadImage();
    }
}
复制代码

好了,简单的mvvm模式大概就是这样,本人能力有限,有很多不足之处,如有大神请指摘,下面贴出代码的GitHub地址:github.com/ale0201/mvv…

你可能感兴趣的:(Android ViewModel+liveData+lifecycle+databinding打造MVVM)