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 onE