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

我的新书《Android App开发入门与实战》已于2020年8月由人民邮电出版社出版,欢迎购买。点击进入详情


欢迎加入Android开发交流QQ群:
Android开发技术交流

关于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

欢迎关注我的技术公众号:国民程序员,我们的目标:输出干货

  1. 每天分享原创技术文章
  2. 海量免费技术资料和视频学习资源
  3. 分享赚钱门道,带领程序员走向财务自由
图片名称
  • 8
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
好的,下面是一个简单的示例: 首先,在build.gradle文件中添加以下依赖项: ```groovy // ViewModel and LiveData implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0' // Data Binding implementation 'androidx.databinding:databinding-runtime:4.0.1' ``` 接下来,创建一个名为MainActivity的Activity,并在其布局文件中添加两个Fragment的占位符: activity_main.xml: ```xml <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <FrameLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent"/> </layout> ``` MainActivity.java: ```java public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main); // 加载第一个Fragment getSupportFragmentManager().beginTransaction() .replace(R.id.container, new FirstFragment()) .commit(); } } ``` 接下来,创建一个名为FirstFragment的Fragment,并在其布局文件中使用DataBinding绑定数据: first_fragment.xml: ```xml <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{viewModel.text}" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Next" android:onClick="@{viewModel::onNextClicked}" /> </LinearLayout> </layout> ``` FirstFragment.java: ```java public class FirstFragment extends Fragment { private FirstViewModel viewModel; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // 使用DataBinding绑定布局文件 FirstFragmentBinding binding = DataBindingUtil.inflate(inflater, R.layout.first_fragment, container, false); // 创建ViewModel实例 viewModel = ViewModelProviders.of(this).get(FirstViewModel.class); // 将ViewModel与布局文件中的变量绑定 binding.setViewModel(viewModel); // 设置LifecycleOwner,以便LiveData知道何时更新UI binding.setLifecycleOwner(this); return binding.getRoot(); } } ``` 下面是FirstViewModel.java: ```java public class FirstViewModel extends ViewModel { private MutableLiveData<String> textLiveData = new MutableLiveData<>(); public FirstViewModel() { // 初始化LiveData的默认值 textLiveData.setValue("Hello, World!"); } public LiveData<String> getText() { return textLiveData; } public void onNextClicked() { // 更新LiveData的值 textLiveData.setValue("Next Clicked!"); } } ``` 最后,创建另一个名为SecondFragment的Fragment,并在MainActivity中添加一个方法来加载它: second_fragment.xml: ```xml <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@{viewModel.text}" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Previous" android:onClick="@{viewModel::onPreviousClicked}" /> </LinearLayout> </layout> ``` SecondFragment.java: ```java public class SecondFragment extends Fragment { private SecondViewModel viewModel; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // 使用DataBinding绑定布局文件 SecondFragmentBinding binding = DataBindingUtil.inflate(inflater, R.layout.second_fragment, container, false); // 创建ViewModel实例 viewModel = ViewModelProviders.of(this).get(SecondViewModel.class); // 将ViewModel与布局文件中的变量绑定 binding.setViewModel(viewModel); // 设置LifecycleOwner,以便LiveData知道何时更新UI binding.setLifecycleOwner(this); return binding.getRoot(); } } ``` 下面是SecondViewModel.java: ```java public class SecondViewModel extends ViewModel { private MutableLiveData<String> textLiveData = new MutableLiveData<>(); public SecondViewModel() { // 初始化LiveData的默认值 textLiveData.setValue("Goodbye, World!"); } public LiveData<String> getText() { return textLiveData; } public void onPreviousClicked() { // 更新LiveData的值 textLiveData.setValue("Previous Clicked!"); } } ``` 最后,在MainActivity中添加一个方法来加载SecondFragment: ```java private void loadSecondFragment() { getSupportFragmentManager().beginTransaction() .replace(R.id.container, new SecondFragment()) .commit(); } ``` 现在,你的MVVM Android项目就完成了!你可以使用LiveDataViewModel来管理数据,并使用DataBinding将数据绑定到UI上。Lifecycle组件可确保UI在活动和片段之间正确地进行管理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值