鸿蒙开发MVVM+Retrofit+OkHttp+RxJava
HarmonyMVVMHttp
刚接触Harmony开发2天!不得不吐槽一下,“远程真机调试”真的好难用还限时,日志还经常不打印(我本以为是Log问题,换了System.out.print也一样,哈哈),经常编译时候卡住,“Attach Debugger to Process”无法使用。开发的好吃力啊!但依然看好鸿蒙OS,拭目以待!
项目地址:https://gitee.com/Liao8180/harmony-mvvmhttp
简介
本项目主要“鸿蒙化”了部分android代码,过去使用MVVM爱不释手,来到鸿蒙后发现没有ViewModel和livedata,又不想用MVP,就试着照搬Android吧!搬完MVVM后,又想在鸿蒙里玩玩Retrofit+OkHttp+RxJava,查了查好像没有鸿蒙化的RxAndroid(项目里我以RxHarmony命名),于是也搬过来吧!搬着搬着发现鸿蒙居然能直接在主线程进行Http请求操作...这个问题没深究,继续搬代码!
温馨提示
本项目仅供参考,不建议直接丢进正式项目开发,如有bug概不负责哈!不熟悉的MVVM的,上百度,这里不做教学,而且我也不懂教(对,就是菜)!
1.MVVM
1.1 ViewModel和LiveData
因为鸿蒙暂时没有提供ViewModel和LiveData的功能,library中直接把Android的ViewModel和LiveData搬过来了。库中的HarmonyViewModel 相对于 AndroidViewModel。
public class HarmonyViewModel extends ViewModel{
private AbilityPackage mApplication;
public HarmonyViewModel(@NonNull AbilityPackage mApplication) {
this.mApplication = mApplication;
}
@SuppressWarnings({"TypeParameterUnusedInFormals", "unchecked"})
@NonNull
public <T extends AbilityPackage> T getApplication() {
return (T) mApplication;
}
@Override
protected void onCleared() {
super.onCleared();
}
}
1.2 ComponentAbility和ComponentAbilitySlice
抽象类ComponentAbility和ComponentAbilitySlice相继继承了Ability和AbilitySlice。主要实现ViewModelStoreOwner接口中getViewModelStore()方法并且绑定生命周期(可参考Android中的ComponentActivity)。所以后续需使用MVVM的话,需使用ComponentAbilitySlice 或 ComponentAbility 。
public abstract class ComponentAbilitySlice extends AbilitySlice implements ViewModelStoreOwner {
private ViewModelStore mViewModelStore;
@Override
protected void onStart(Intent intent) {
super.onStart(intent);
getLifecycle().addObserver(new LifecycleStateObserver() {
@Override
public void onStateChanged(Lifecycle.Event event, Intent intent) {
if (event == Lifecycle.Event.ON_STOP) {
getViewModelStore().clear();
}
}
});
}
@Override
public ViewModelStore getViewModelStore() {
if (getAbility().getAbilityPackage() == null) {
throw new IllegalStateException("Your ability is not yet attached to the "
+ "AbilityPackage instance. You can't request ViewModel before onStart call.");
}
if (mViewModelStore == null) {
mViewModelStore = new ViewModelStore();
}
return mViewModelStore;
}
}
public abstract class ComponentAbility extends Ability implements ViewModelStoreOwner {
private ViewModelStore mViewModelStore;
@Override
protected void onStart(Intent intent) {
super.onStart(intent);
getLifecycle().addObserver(new LifecycleStateObserver() {
@Override
public void onStateChanged(Lifecycle.Event event, Intent intent) {
if (event == Lifecycle.Event.ON_STOP) {
getViewModelStore().clear();
}
}
});
}
@Override
public ViewModelStore getViewModelStore() {
if (getAbilityPackage() == null) {
throw new IllegalStateException("Your ability is not yet attached to the "
+ "AbilityPackage instance. You can't request ViewModel before onStart call.");
}
if (mViewModelStore == null) {
mViewModelStore = new ViewModelStore();
}
return mViewModelStore;
}
}
可能会有同学问,为什么没有Fraction的啊?
如果需要Fraction的同学,也可以照葫芦画瓢的写一个ComponentFraction和ComponentFractionAbility。我为什么没写是因为“懒”!
1.3 项目中的BaseViewModel、BaseVMAbilitySlice和BaseVMAbility 抽象类
Base系列大家应该都懂,这里不做过多描述。大家可以根据各自需求丰富各自的Base。
1.3.1 BaseViewModel
此处BaseViewModel仅仅定义了ViewModelProvider工厂和提供创建ViewModelProvider工厂的方法。
public abstract class BaseViewModel extends HarmonyViewModel {
protected String TAG = this.getClass().getSimpleName();
public BaseViewModel(AbilityPackage mApplication) {
super(mApplication);
}
public static <T extends BaseViewModel> ViewModelProvider.Factory createViewModelFactory(T viewModel) {
return new ViewModelFactory(viewModel);
}
static class ViewModelFactory implements ViewModelProvider.Factory {
BaseViewModel viewModel;
public ViewModelFactory(BaseViewModel viewModel) {
this.viewModel = viewModel;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) viewModel;
}
}
@Override
protected void onCleared() {
super.onCleared();
}
}
1.3.2 BaseVMAbilitySlice和BaseVMAbility
BaseVMAbilitySlice和BaseVMAbility通过泛型和抽象方法实例化ViewModel和布局。
public abstract class BaseVMAbilitySlice<VM extends BaseViewModel> extends ComponentAbilitySlice {
protected String TAG = this.getClass().getSimpleName();
protected VM mViewModel;
@SuppressWarnings("unchecked")
@Override
protected void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(getUIContent());
VM vm = createViewModel();
mViewModel = (VM) new ViewModelProvider(this,BaseViewModel.createViewModelFactory(vm)).get(vm.getClass());
init(intent);
}
/**
* 获取布局id
* @return
*/
protected abstract int getUIContent();
/**
* 获取ViewModel实例
* @return
*/
protected abstract VM createViewModel();
/**
* 初始化
*/
protected abstract void init(Intent intent);
}
2. Retrofit+OkHttp+RxJava
这个我就不细说了,Android开发时候大家应该都知道有RxAndroid这玩意吧(io.reactivex.rxjava3:rxandroid),我这里仅仅把它鸿蒙化了而已,可参考library中的rx_harmony文件夹。具体实现差不多,只是RxAndroid封装了Handler的实现,鸿蒙这里我用鸿蒙的EventHandler。
具体实现如下:
Disposable disposable = HttpHelper.getApi().getTestData()
.compose(RxScheduler.Flo_io_main())
.subscribeWith(new CommonSubscriber<BaseResponse<List<TestDataBean>>>() {
// @Override
// protected void onStart() {
// super.onStart();
// //这里可以告知UI启动Loading弹框
// }
@Override
protected void onSuccess(@NonNull BaseResponse<List<TestDataBean>> listBaseResponse) {
//通过MutableLiveData将请求获取的数据传到Ability或AbilitySlice中刷新页面。
data.setValue(listBaseResponse.getData());
}
@Override
protected void onFail(String msg) {
//异常
}
@Override
protected void onFinish() {
//请求结束
}
});
最后别忘了在onCleared()中处理disposable啊!
@Override
protected void onCleared() {
super.onCleared();
//处理disposable
if (disposable != null && !disposable.isDisposed()){
disposable.dispose();
}
}
有同学会问,如果页面有N个请求那不是要判断N个disposable和dispose N个?这里大家可以根据自己项目情况实现抽象类BaseViewModel并加入以下变量和方法,并且在onCleared()处理unSubscribe():
private CompositeDisposable mCompositeDisposable;
/**
* 结束所有disposable
*/
public void unSubscribe() {
if (mCompositeDisposable != null) {
mCompositeDisposable.dispose();
}
}
/**
* 移除指定disposable
* @param subscription
*/
public void removeSubscribe(Disposable subscription) {
if (subscription == null || mCompositeDisposable == null) {
return;
}
mCompositeDisposable.remove(subscription);
}
/**
* 添加disposable
* @param subscription
*/
public void addSubscribe(Disposable subscription) {
if (mCompositeDisposable == null) {
mCompositeDisposable = new CompositeDisposable();
}
mCompositeDisposable.add(subscription);
}
@Override
protected void onCleared() {
super.onCleared();
unSubscribe();
}
当然Disposable的处理方式还有很多种,大家可以百度查查。可能我个人原因,不太喜欢在base中做太多功能实现,如需要一般都会通过子类去实现。
好了,就到这,有问题可以留言,在我能力范围内尽力回复。88