关于Jetpack是什么东西,Google Architecture Componet又是啥玩意,这里就不做描述了,如果你不知道,那你得先了解下这些东东。
本文主要描述的是基于自己的理解,如何将这一套框架融合起来,形成一套完成可复用的通用型框架。官方大图镇楼:
首先来描述一个比较通用的场景,网络请求->解析json->绑定adapter->展示UI。下面一步步来分析。
看上图,我们从上往下构建。
网络层
我这层用retrofit,就不解释了,至于你用的啥,其实影响不大。至于怎么封装retrofit,每个人有每个人的写法,也就不做描述了。但是大体上都会有这么一段代码
interface XXAPI{
getList(@Field("page")page:Int): Single>;
}
PageList的构造
datasource有了,那我们就得用pagelist把datasource给糅合起来.
先来个ListDataSource:
class ListDataSource(remoteData:(page:Int)->Single>,
compositeDisposable:CompositeDisosable
):PageKeyedDataSource() {
val networkState = MutableLiveData()
val initialLoad = MutableLiveData()
val newDataArrive = SingleLiveEvent()
override fun loadInitial(params: LoadInitialParams, callback: LoadInitialCallback) {
// update network states.
// we also provide an initial load state to the listeners so that the UI can know when the
// very first list is loaded.
networkState.postValue(NetworkState.LOADING)
initialLoad.postValue(NetworkState.LOADING)
//get the initial users from the api
compositeDisposable.add(
remoteData.invoke(1)
.subscribe({ items ->
// clear retry since last request succeeded
setRetry(null)
networkState.postValue(NetworkState.LOADED)
initialLoad.postValue(NetworkState.LOADED)
callback.onResult(items, null, 2)
newDataArrive.postCall()
}, { throwable ->
newDataArrive.postCall()
// keep a Completable for future retry
setRetry(Action { loadInitial(params, callback) })
val error = NetworkState.error(throwable)
// publish the error
networkState.postValue(error)
initialLoad.postValue(error)
}))
}
override fun loadAfter(params: LoadParams, callback: LoadCallback) {
// set network value to loading.
networkState.postValue(NetworkState.LOADING)
//get the users from the api after id
compositeDisposable.add(remoteData.invoke(params.key).subscribe({ items ->
// clear retry since last request succeeded
setRetry(null)
networkState.postValue(NetworkState.LOADED)
callback.onResult(items, params.key+1)
newDataArrive.postCall()
}, { throwable ->
// keep a Completable for future retry
setRetry(Action { loadAfter(params, callback) })
// publish the error
networkState.postValue(NetworkState.error(throwable))
}))
}
override fun loadBefore(params: LoadParams, callback: LoadCallback) {
// set network value to loading.
networkState.postValue(NetworkState.LOADING)
//get the users from the api after id
compositeDisposable.add(remoteData.invoke(params.key).subscribe({ items ->
// clear retry since last request succeeded
setRetry(null)
networkState.postValue(NetworkState.LOADED)
callback.onResult(items, params.key-1)
newDataArrive.postCall()
}, { throwable ->
// keep a Completable for future retry
setRetry(Action { loadAfter(params, callback) })
// publish the error
networkState.postValue(NetworkState.error(throwable))
}))
}
/**
* Keep Completable reference for the retry event
*/
private var retryCompletable: Completable? = null
fun retry() {
if (retryCompletable != null) {
compositeDisposable.add(retryCompletable!!
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ }, { throwable -> Log.e("ListDataSource",throwable.message) }))
}
}
private fun setRetry(action: Action?) {
if (action == null) {
this.retryCompletable = null
} else {
this.retryCompletable = Completable.fromAction(action)
}
}
}
分析一下这段代码:
1、构造函数是两个参数,第一个是我们网络请求方法的返回值,第二个是CompositeDisosable,就是用来把rxjava放进去,然后好管理的容器。
2、networkstate,网络状态,加载中,加载成功,加载失败。代码如下
enum class Status {
RUNNING,
SUCCESS,
FAILED
}
@Suppress("DataClassPrivateConstructor")
data class NetworkState private constructor(
val status: Status,
val throwable: Throwable? = null) {
companion object {
val LOADED = NetworkState(Status.SUCCESS)
val LOADING = NetworkState(Status.RUNNING)
fun error(throwable: Throwable?) = NetworkState(Status.FAILED, throwable)
}
}
3、两个变量 initialLoad 和 newDataArrive 第一个是初始化的networkstate的Livedata状态,第二个也是个livedata,只是封装了不用发变量的方法,代码如下:
public class SingleLiveEvent extends MutableLiveData {
private static final String TAG = "SingleLiveEvent";
private final AtomicBoolean mPending = new AtomicBoolean(false);
@MainThread
@Override
public void observe(LifecycleOwner owner, final Observer super T> observer) {
if (hasActiveObservers()) {
Log.w(TAG, "Multiple observers registered but only one will be notified of changes.");
}
// Observe the internal MutableLiveData
super.observe(owner, new Observer() {
@Override
public void onChanged(@Nullable T t) {
if (mPending.compareAndSet(true, false)) {
observer.onChanged(t);
}
}
});
}
@MainThread
@Override
public void setValue(@Nullable T t) {
mPending.set(true);
super.setValue(t);
}
/**
* Used for cases where T is Void, to make calls cleaner.
*/
@MainThread
public void call() {
setValue(null);
}
public void postCall() {
postValue(null);
}
}
4、然后是两个系统的回调方法,里面的操作,就是先初始化网络状态值,然后把请求添加到compositeDisposable中
然后再来个datasourcefactory 把上面的datasource给放进去
class ListDataSourceFactory(
private val remoteData: (page:Int)-> Single>,
private val compositeDisposable: CompositeDisposable
): DataSource.Factory() {
val listDataSource = MutableLiveData>()
override fun create(): DataSource {
val myDesignDataSource = ListDataSource(remoteData, compositeDisposable)
listDataSource.postValue(myDesignDataSource)
return myDesignDataSource
}
}
代码很简单,就是系统的方法重写一下返回我们的listdatasource
ViewModel
数据有了,这个时候我们得来个viewmodel来承载了。
open abstract class ListViewModel : ViewModel() {
private val compositeDisposable = CompositeDisposable()
private val sourceFactory: ListDataSourceFactory
private lateinit var designList: LiveData>
var beforeItems = MutableLiveData>()
private var mutableList = mutableListOf()
var mutableItems = MutableLiveData>()
var items = MutableLiveData>()
init {
sourceFactory = ListDataSourceFactory(dataProvider(), compositeDisposable)
}
private var firstTime = true
val refreshEvent = MutableLiveData()
val retry = {
items.apply {
(value?.size == 0).yes {
// value 为null标示界面不会显示无
this.value = null
}
}
refreshEvent.postValue(true)
}
val refresh = {
firstTime = false
refresh()
}
val loadMore = {
designList.value?.apply {
val index = if (items.value != null) {
items.value!!.size
} else {
0
}
loadAround(index)
}
}
fun loadMainData() {
val config = PagedList.Config.Builder()
.setPageSize(20)
.setInitialLoadSizeHint(20)
.setEnablePlaceholders(false)
.build()
designList = LivePagedListBuilder(sourceFactory, config).build()
designList.observeForever {
sourceFactory.listDataSource.value!!.newDataArrive.observeForever {
designList.value.let {
if(it == null){
convert(listOf())
}else{
convert(it)
}
}.let {
items.postValue(it)
mutableList.clear()
beforeItems.value?.run {
mutableList.addAll(this)
}
mutableList.addAll(it)
mutableItems.postValue(mutableList)
}
}
}
}
private瞎 fun retry() {
sourceFactory.listDataSource.value?.retry()
}
private fun refresh() {
sourceFactory.listDataSource.value?.invalidate()
}
fun dataEnd(): LiveData = Transformations.switchMap, Boolean>(
sourceFactory.listDataSource, { Transformations.map(it.networkState, { it.status == Status.FAILED && it.throwable != null && it.throwable.noData() }) }
)
fun networkState(): LiveData = Transformations.switchMap, NetworkState>(
sourceFactory.listDataSource, { it.networkState })
fun initNetError(): LiveData = Transformations.switchMap, Boolean>(
sourceFactory.listDataSource, { Transformations.map(it.initialLoad, { it.status == Status.FAILED && it.throwable != null && it.throwable.netError() }) }
)
fun loading(): LiveData = Transformations.switchMap, Boolean>(
sourceFactory.listDataSource, { Transformations.map(it.initialLoad, { it.status == Status.RUNNING && firstTime }) }
)
override fun onCleared() {
super.onCleared()
compositeDisposable.dispose()
}
abstract fun dataProvider(): (page: Int) -> Single>
abstract fun convert(list: List): List
}
再来解释一波代码:
1、在init初始化中,初始化了一个listdatasource,然后加了个dataProvider抽象方法,这方法呢,就是我们通常分页加载掉接口的那个方法了
2、loadMainData方法,首先是builder了一个pagelist的config,然后用一个LivePagedListBuilder来创建一个LiveData
3、convert抽象方法,是供我们用来转换的方法
4、下面的那几个retry、refresh 、loadmore就分别对应了我们的刷新重试,加载更多,其中还有一些根据网络状态显示不同UI 的操作了,
恩。整体上的封装,就是这样了。这里有个具体例子 综合了一些操作,但是好像没写完或者有错。。恩恩,后续在完善,可以当做一些参考,