接下来到了封装ViewModel的时候了
一、BaseViewModel
public abstract class BaseViewModel<R extends BaseRepository> extends ViewModel implements LifecycleObserver {
protected R mRepository;
/**
* UI改变 LiveData管理器
*/
private UIChangeLiveDataManager mUiChangeLiveDataManager;
/**
* Disposable容器
*/
private CompositeDisposable mCompositeDisposable;
/**
* 连续双击退出应用
*/
protected boolean mExitApp;
public BaseViewModel(R repository) {
this.mRepository = repository;
registerEventBus();
}
/**
* 注册EventBus
*/
private void registerEventBus() {
//绑定EventBus
if (this.getClass().isAnnotationPresent(BindEventBus.class)
&& !EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().register(this);
}
}
/**
* 解注册EventBus
*/
private void unregisterEventBus() {
//解绑EventBus
if (this.getClass().isAnnotationPresent(BindEventBus.class)
&& EventBus.getDefault().isRegistered(this)) {
EventBus.getDefault().unregister(this);
}
}
/**
* 获取 UI改变 LiveData管理器
*
* @return UI改变 LiveData管理器
*/
public UIChangeLiveDataManager getUiChangeLiveDataManager() {
if (mUiChangeLiveDataManager == null) {
mUiChangeLiveDataManager = new UIChangeLiveDataManager();
}
return mUiChangeLiveDataManager;
}
/**
* 显示加载中Dialog
*
* @param hint 提示文本
*/
public void showLoadingDialog(@NonNull String hint) {
getUiChangeLiveDataManager().getShowLoadingDialogEvent().postValue(hint);
}
/**
* 隐藏加载中Dialog
*/
public void hideLoadingDialog() {
getUiChangeLiveDataManager().getHideLoadingDialogEvent().call();
}
/**
* 通过Class跳转界面
**/
public void startActivity(Class<?> cls) {
startActivity(cls, null);
}
/**
* 通过Class跳转界面 (有结果返回)
*
* @param cls 要跳转到的Activity
* @param requestCode 请求码
**/
public void startActivityForResult(Class<?> cls, int requestCode) {
startActivityForResult(cls, null, requestCode);
}
/**
* 含有Bundle通过Class跳转界面
*
* @param cls 要跳转到的Activity
* @param bundle 携带的数据
**/
public void startActivity(Class<?> cls, Bundle bundle) {
final SparseArray<Object> paramSA = new SparseArray<>(2);
paramSA.put(ParamConstant.CLASS, cls);
if (bundle != null) {
paramSA.put(ParamConstant.BUNDLE, bundle);
}
getUiChangeLiveDataManager().getStartActivityEvent().postValue(paramSA);
}
/**
* 含有Bundle通过Class跳转界面
*
* @param cls 要跳转到的Activity
* @param bundle 要携带的数据
* @param requestCode 请求码
**/
public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
final SparseArray<Object> paramSA = new SparseArray<>(3);
paramSA.put(ParamConstant.CLASS, cls);
if (bundle != null) {
paramSA.put(ParamConstant.BUNDLE, bundle);
}
paramSA.put(ParamConstant.REQUEST_CODE, requestCode);
getUiChangeLiveDataManager().getStartActivityEvent().postValue(paramSA);
}
/**
* 销毁Activity
*/
public void finish() {
getUiChangeLiveDataManager().getFinishEvent().call();
}
/**
* 指定间隔时间内 按下两次返回键退出App
*/
public void doubleDownExitApp() {
if (mExitApp) {
//关闭所有的Activity
ActivityUtils.finishAllActivities();
} else {
mExitApp = true;
ToastUtils.showShort("再按一次退出应用");
//超过两秒没有再次点击,则不退出App
new Handler().postDelayed(() -> mExitApp = false, 2000);
}
}
/**
* ViewModel销毁回调
*/
@Override
protected void onCleared() {
super.onCleared();
//解注册EventBus
//unregisterEventBus();
//取消所有异步任务
clearDisposable();
//销毁Model
if (mRepository != null) {
mRepository.onCleared();
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_ANY)
protected void onAny(LifecycleOwner owner, Lifecycle.Event event) {
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
protected void onCreate() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
protected void onStart() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
protected void onResume() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
protected void onPause() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
protected void onStop() {
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
protected void onDestroy() {
}
/**
* UI改变 LiveData管理器
*/
public static class UIChangeLiveDataManager {
private SingleLiveEvent<String> showLoadingDialogEvent;
private SingleLiveEvent<Object> hideLoadingDialogEvent;
private SingleLiveEvent<SparseArray<Object>> startActivityEvent;
private SingleLiveEvent<Object> finishEvent;
/**
* 获取 显示加载中Dialog SingleLiveEvent
*
* @return 显示加载中Dialog SingleLiveEvent
*/
public SingleLiveEvent<String> getShowLoadingDialogEvent() {
if (showLoadingDialogEvent == null) {
showLoadingDialogEvent = new SingleLiveEvent<>();
}
return showLoadingDialogEvent;
}
/**
* 获取 隐藏加载中Dialog SingleLiveEvent
*
* @return 隐藏加载中Dialog SingleLiveEvent
*/
public SingleLiveEvent<Object> getHideLoadingDialogEvent() {
if (hideLoadingDialogEvent == null) {
hideLoadingDialogEvent = new SingleLiveEvent<>();
}
return hideLoadingDialogEvent;
}
/**
* 获取 跳转Activity SingleLiveEvent
*
* @return 跳转Activity SingleLiveEvent
*/
public SingleLiveEvent<SparseArray<Object>> getStartActivityEvent() {
if (startActivityEvent == null) {
startActivityEvent = new SingleLiveEvent<>();
}
return startActivityEvent;
}
/**
* 获取 关闭销毁Activity SingleLiveEvent
*
* @return 关闭销毁Activity SingleLiveEvent
*/
public SingleLiveEvent<Object> getFinishEvent() {
if (finishEvent == null) {
finishEvent = new SingleLiveEvent<>();
}
return finishEvent;
}
}
/**
* 静态常量
*/
public static class ParamConstant {
/**
* Class
*/
public static final int CLASS = 1;
/**
* Bundle数据
*/
public static final int BUNDLE = 2;
/**
* 请求码
*/
public static final int REQUEST_CODE = 3;
/**
* Activity Class 全限定名称
*/
public static final int CANONICAL_NAME = 4;
}
}
这里的mRepository是网络数据操作类用来封装和服务器交互数据的
public abstract class BaseRepository {
protected BaseNetworkSource mNetworkSource;
/**
* 设置网络源
*
* @param networkSource 网络源
* @param <T> 泛型
* @return Repository
*/
public final <T extends BaseRepository> T setNetworkSource(@NonNull BaseNetworkSource networkSource) {
this.mNetworkSource = networkSource;
return CastUtil.cast(this);
}
/**
* 获取子类类型实例
*
* @param <T> 泛型
* @return 子类类型实例
*/
public final <T extends BaseRepository> T get() {
return CastUtil.cast(this);
}
/**
* 销毁回调
*/
public void onCleared() {
if (mNetworkSource != null) {
mNetworkSource.onCleared();
}
}
}
最后这里暂时不解释了,直接粘代码,设计的还是有点缺陷,等我改正之后再重新整理这里吧
public class AClassNetworkSource extends BaseNetworkSource implements IAClassNetworkSource {
private ServerApi mServerApi;
private AClassNetworkSource() {
this.mServerApi = RetrofitUtil.getInstance().create(ServerApi.class);
}
public static AClassNetworkSourcecreate() {
return new AClassNetworkSource();
}
@Override
public void login(@NonNull Map<String, Object> postMap, @NonNull OnResultListener<ResultBean<LoginBean>, String> listener) {
mServerApi
.login(postMap)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((ResultBean<LoginBean> result) -> {
if (result.code == SUCCESS) {
listener.onSuccess(result);
} else {
listener.onFailure(result.msg, null);
}
}, (Throwable throwable) -> {
listener.onFailure("登录失败", throwable);
});
}
}
网络连接泛型
public interface ILoginNetworkSource {
/**
* 登录
*
* @param postMap 数据
* @param listener 回调监听
*/
void login(@NonNull Map<String, Object> postMap, @NonNull OnResultListener<ResultBean<LoginBean>, String> listener);
}
DemoActivity的ViewModel实现类:
public class AClass extends BaseViewModel<AClassRepository> {
public AClass(AClassRepository repository) {
super(repository);
});
}
//电话号
public ObservableField<String> username= new ObservableField<>("");
//密码
public ObservableField<String> password = new ObservableField<>("");
//登录
public View.OnClickListener loginClick = v -> {
clickLogin();
};
public void clickLogin() {
if (ObjectUtils.isEmpty(username.get())) {
ToastUtils.showShort("请输入账号");
return;
}
if (ObjectUtils.isEmpty(password.get())) {
ToastUtils.showShort("请输入密码");
return;
}
Map<String, Object> postMap = new HashMap<>();
postMap.put("username", username.get());
postMap.put("password", password.get());
mRepository.login(postMap, new OnResultListener<ResultBean<LoginBean>, String>() {
@Override
public void onSuccess(ResultBean<LoginBean> data) {
super.onSuccess(data);
}
@Override
public void onFailure(String data, Throwable e) {
super.onFailure(data, e);
}
});
}
}
网络通信数据类:
public class AClassRepository extends BaseRepository implements IAClassNetworkSource {
private AClassRepository() {}
public static AClassRepository create() {
return new AClassRepository();
}
@Override
public void login(@NonNull Map<String, Object> postMap, @NonNull OnResultListener<ResultBean<LoginBean>, String> listener) {
if (mNetworkSource != null) {
IAClassNetworkSource aClassNetworkSource = mNetworkSource.get();
aClassNetworkSource .login(postMap, listener);
} else {
throw new IllegalArgumentException("网络源不能为空");
}
}
}