1,前言
这篇文章写的是数据加载和分页。用到的库有
'androidx.lifecycle:lifecycle-service:2.4.0' 'androidx.lifecycle:lifecycle-extensions:2.2.0' 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0'
io.reactivex.rxjava3:rxjava:3.0.4
io.reactivex.rxjava3:rxandroid:3.0.0
androidx.lifecycle:lifecycle-livedata-ktx:2.1.0
代码有些地方一开始设计的时候多想了,其实有些地方设计不太好,不过不影响实际代码,我就暂时没改
2.开始
1)基本接口
->这里混合了kotlin java,因为一开始写的时候是java后面用kotlin写
/**
* 书本目录的接口
*/
public interface Book {
/**
* 当前一页加载的数据
* @return
*/
int pageSize();
/**
* 从哪一页开始
* @return
*/
int thisStartPage();
}
/**
* 数据加载接口
* @param Entity
*/
interface IDataEngine<Entity> : Book {
fun getRemoteData(page: Int): Observable<Entity>?
}
/**
* 书本数据加载的一个基本引擎接口
* 具有从新加载,分页,最后页数,总阅览(realData)数据等业务
*/
interface IPageEngine<Item> : Book, ISource<Item> {
fun refresh()
operator fun next()
fun state(): Int
fun loadState(): Int
fun page(): Int
fun lastSize(): Int
/**
* page id的
* 如果刷新,那么此id就会更新。他的含义就是此次刷新数据组的id,下拉不会改变此数值
*
* @param observer Observer<Int>
*/
fun registerPageIdObserver(observer: Observer<Int>)
companion object {
const val NONE: Int = -1
const val STATE_END_REFRASH = 991
const val STATE_START_NEXT = 996
const val STATE_START_REFRASH = 998
const val STATE_END_ERROR = 997
const val STATE_END_NEXT = 992
const val NO_MORE_PAGE = 993
const val PAGE_SIZE = 20
}
}
/**
* 返回一个lifecycle
*/
interface ILifeObject{
fun lifecycleOwner(): LifecycleOwner?
}
/**
* 处理数据
* @param <T>
*/
public interface DataBusiness<T> {
void handlerData(T t, int action);
}
2)核心实现类 PageSupport.class
/**
* Book ,此类是分页加载具体实现类
*
* @param <ListItem> 每项数据的泛型{@link #data}
* @param <DataEntity> remote 数据端加载进入来的未过滤的基本数据泛型 通过{@link CallBack#transformDataToList(DataEntity)} 转化成{@link #data}
*/
public class PageSupport<ListItem, DataEntity> implements IPageEngine<ListItem>, Observer<DataEntity> {
private static final String TAG = "PageSupport";
/**
* 分页的最基本的数据存储原型
*/
private final List<ListItem> data = new SgArrayList<>();
// /**
// * 是否正在加载
// */
// private boolean isLoaderNow = false;
/**
* 一个提供给外部实现的回调函数
* 用户处理不同业务情况
*/
protected CallBack<ListItem, DataEntity> callBack;
/**
* 最后一此的数据长度
*/
private int lastSize = 0;
private int size2 = 0;
private int maxPage = -1;
private boolean isEndPage = false;
private final MutableLiveData<Integer> state = new MediatorLiveData<Integer>();
private final MutableLiveData<Integer> size = new MutableLiveData<>();
private final MutableLiveData<Integer> page = new MutableLiveData<Integer>() {
@Override
public void setValue(Integer value) {
// if (isLoaderNow) {
// ToastUtil.s("正在拼命加载~");
// return;
// }
// isLoaderNow = true;
if (Thread.currentThread() != Looper.getMainLooper().getThread()) {
super.postValue(value);
return;
}
super.setValue(value);
}
};
private final MutableLiveData<Integer> loadId = new MutableLiveData<>(0);
private FlashObserver<DataEntity> mFlashObserver;
//