MVVM架构:LiveData + ViewModel + Repository搭配的三种解决方案

关于MVVM

关于MVVM的介绍,我们可以参考之前的文章:
Android App开发架构之:MVVM

和MVP相比,MVVM有相似的地方,也有各自的特点。
相似点:

  1. MVVM的VM层对应于MVP的P层;
  2. MVVM的M层对应于MVP的M层;
  3. 两者的V层一样,对应着fragment和activity等view界面;

区别:
4. MVVM使用LiveData,LiveData是一个具有生命周期感知功能的数据持有者类;也就是使用LiveData时,可以不用关心activity和fragment的生命周期可能带来的内存泄漏问题,因为LiveData会在activity和fragment生命周期结束时立即取消订阅。
5. MVP为了解决内存泄漏,需要手动实现,比如采用弱引用,或者RxJava的Disposable、RxLifecycle或者AutoDispose方案。参考:TinyMVP:一种全方案解决内存泄漏的MVP架构

解决方案

同TinyMVP,TinyMVVM的ViewModel和Repository也是通过泛型来自动生成实例:

public class Type1Activity extends BaseMVVMActivity<Type1ViewModel> {
......
}

public class Type1ViewModel extends BaseViewModel<Type1Repository> {
......
}

接下来会有三种形式的使用方式:

方案1

ViewModel只负责业务接口;
Repository负责LiveData变量生成以及数据处理;

通过代码可以看到,这里的Type1ViewModel提供V层调用的接口loadData1和loadData2;
并且通过getLiveData1和getLiveData2提供给V层livedata变量;

public class Type1ViewModel extends BaseViewModel<Type1Repository> {

    public Type1ViewModel(@NonNull Application application) {
        super(application);
    }

    public LiveData<Boolean> getLiveData1() {
        return repository.getLiveData1();
    }

    public LiveData<String> getLiveData2() {
        return repository.getLiveData2();
    }

    public void loadData1() {
        repository.getData1();
    }

    public void loadData2() {
        repository.getData2();
    }
}

Type1Repository负责提供livedata变量比如mLiveData1、mLiveData2,已经具体获取数据的方法如getData1、getData2;

public class Type1Repository extends BaseRepository {

    protected MutableLiveData<Boolean> mLiveData1;
    protected MutableLiveData<String> mLiveData2;

    public LiveData<Boolean> getLiveData1() {
        if (mLiveData1 == null) {
            mLiveData1 =  new MutableLiveData<>();
        }
        return mLiveData1;
    }

    public LiveData<String> getLiveData2() {
        if (mLiveData2 == null) {
            mLiveData2 =  new MutableLiveData<>();
        }
        return mLiveData2;
    }

    public void getData1() {

        Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
            try {
                Thread.sleep(2000); // 假设此处是耗时操作
            } catch (Exception e) {
                e.printStackTrace();
                emitter.onError(new RuntimeException());
            }
            emitter.onNext(true);
        }
        )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Boolean orderValues) {
                        mLiveData1.setValue(orderValues);
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    public void getData2() {
    ......
    }
}

方案2

ViewModel负责业务变量接口以及LiveData变量;
Repository负责获取数据,Repository和ViewModel之间如果涉及到异步调用问题,Repository的方法采用RxJava的Observable的返回值类型,返回给ViewModel调用方处理。

通过代码可以看到,Type2ViewModel生成了mLiveData1和mLiveData2变量,这些变量可以通过getLiveData1和getLiveData2供V层调用,并且提供了getLiveData1和getLiveData1方法。

public class Type2ViewModel extends BaseViewModel<Type2Repository> {

    protected MutableLiveData<Boolean> mLiveData1;
    protected MutableLiveData<String> mLiveData2;

    public Type2ViewModel(@NonNull Application application) {
        super(application);
    }

    public LiveData<Boolean> getLiveData1() {
        if (mLiveData1 == null) {
            mLiveData1 = new MutableLiveData<>();
        }
        return mLiveData1;
    }

    public LiveData<String> getLiveData2() {
        if (mLiveData2 == null) {
            mLiveData2 = new MutableLiveData<>();
        }
        return mLiveData2;
    }

    public void loadData1() {
        repository.getData1().subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean orderValues) {
                mLiveData1.setValue(orderValues);
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

    public void loadData2() {
        ......
    }
}

而Type2Repository的getData1和getData2由于异步处理数据,返回了Observable类型。

public class Type2Repository extends BaseRepository {

    public Observable<Boolean> getData1() {

        return Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
            try {
                Thread.sleep(2000); // 假设此处是耗时操作
            } catch (Exception e) {
                e.printStackTrace();
                emitter.onError(new RuntimeException());
            }
            emitter.onNext(true);
        }
        )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }

    public Observable<String> getData2() {
		......
    }
}

方案3(推荐)

方案1和方案2都涉及到了LiveData类型的创建和使用,要么在ViewModel中创建,要么在Repository中创建。如果在Repository中创建,那么还得通过ViewModel让V层得到。

那么我们是否可以考虑将LiveData的创建和使用都统一管理起来呢,就像异步分发的EventBus这样。通过类似于EventBus这样的异步分发管理机制,我们可以在任意地方创建LiveData,并且可以在想要用到的地方获取到LiveData。

我们考虑使用单例和一个HashMap来实现,提供register和post功能:

public class TinyLiveBus {

    private ConcurrentHashMap<String, MutableLiveData<Object>> liveDatas = new ConcurrentHashMap<>();

    private static volatile TinyLiveBus sTinyBus;

    public static TinyLiveBus getInstance() {
        if (sTinyBus == null) {
            return sTinyBus = new TinyLiveBus();
        }
        return sTinyBus;
    }

    public <T> MutableLiveData<T> register(String key, Class<T> clazz) {
        if (!liveDatas.containsKey(key)) {
            liveDatas.put(key, new MutableLiveData<>());
        }
        return (MutableLiveData<T>) liveDatas.get(key);
    }

    public <T> void post(String key, T value) {
        if (liveDatas.containsKey(key)) {
            MutableLiveData liveData = liveDatas.get(key);
            liveData.postValue(value);
        }
    }
}

注:这里postValue表示在子线程和主线程里都可以使用,而setValue只能在主线程中使用。

在Activity中,我们通过TinyLiveBus.getInstance().register方法创建LiveData:

public class Type3Activity extends BaseMVVMActivity<Type3ViewModel> {

    @Override
    protected int getContentView() {
        return R.layout.activity_type;
    }

    @Override
    protected void init() {
        Button btn = findViewById(R.id.button);
        TinyLiveBus.getInstance()
                .register("one", Boolean.class)
                .observe(this, (Observer<Boolean>) bool -> btn.setText(bool ? "success" : "fail"));
        Button btn2 = findViewById(R.id.button2);
        TinyLiveBus.getInstance()
                .register("two", String.class)
                .observe(this, (Observer<String>) string -> btn2.setText(string));
    }

    public void clickMe(View view) {
        mViewModel.loadData1();
    }

    public void clickOther(View view) {
        mViewModel.loadData2();
    }
}

在Repository中,我们通过TinyLiveBus.getInstance().post()通过LiveData有更新:

public class Type3Repository extends BaseRepository {

    public void getData1() {

        Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
            try {
                Thread.sleep(2000); // 假设此处是耗时操作
            } catch (Exception e) {
                e.printStackTrace();
                emitter.onError(new RuntimeException());
            }
            emitter.onNext(true);
        }
        )
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Boolean orderValues) {
                        TinyLiveBus.getInstance().post("one", orderValues);
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    public void getData2() {
    	......
    }
}

github地址

https://github.com/ddnosh/android-tiny-mvvm在这里插入图片描述
公众号:Android开发之路
分享Android、Kotlin、Flutter、Java相关技术,紧跟技术步伐,迈向高级开发。

图片名称

猜你喜欢

转载自blog.csdn.net/ddnosh/article/details/101903615