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

public class Type1ViewModel extends BaseViewModel {

public Type1ViewModel(@NonNull Application application) {

super(application);

}

public LiveData getLiveData1() {

return repository.getLiveData1();

}

public LiveData 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 mLiveData1;

protected MutableLiveData mLiveData2;

public LiveData getLiveData1() {

if (mLiveData1 == null) {

mLiveData1 = new MutableLiveData<>();

}

return mLiveData1;

}

public LiveData getLiveData2() {

if (mLiveData2 == null) {

mLiveData2 = new MutableLiveData<>();

}

return mLiveData2;

}

public void getData1() {

Observable.create((ObservableOnSubscribe) 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() {

@Override

public void onSubscribe(Disposable d) {

}

@Override

public void onNext(Boolean orderValues) {

mLiveData1.setValue(orderValues);

}

@Override

public void onErr

  • 22
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值