nilupeng
2022-08-11 485c4e60955d1a9e82c9887da7d8b71ad68ad257
app/src/main/java/com/runt/open/mvvm/base/model/LoadPageViewModel.java
@@ -1,17 +1,14 @@
package com.runt.open.mvvm.base.model;
import androidx.lifecycle.MutableLiveData;
import com.google.gson.Gson;
import com.runt.open.mvvm.data.HttpApiResult;
import com.runt.open.mvvm.data.PageResult;
import com.runt.open.mvvm.retrofit.observable.HttpObserver;
import org.json.JSONObject;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
@@ -21,7 +18,7 @@
public abstract class LoadPageViewModel<D> extends BaseViewModel {
    public final int SIZE = 10;
    private MutableLiveData<List<D>> liveData = new MutableLiveData<>();
    private MutableLiveData<ArrayList<D>> liveData = new MutableLiveData<>();
    private MutableLiveData liveFailed = new MutableLiveData();
    /**
@@ -32,17 +29,20 @@
    /**
     * 数据请求
     */
    /**
     * 数据请求
     * @param page  页数
     * @param param 请求参数
     */
    public void requestData(int page,Map param){
    public void requestData(int page, Map param){
        final ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
        Class<D> entityClass = (Class<D>) type.getActualTypeArguments()[0];
        httpObserverOn( commonApi.getPageData(requestUrl(), page, SIZE, param), new HttpObserver<PageResult>() {
            @Override
            protected void onSuccess(PageResult data) {
                //数据转换
                List<D> list = new ArrayList<>();
                ArrayList<D> list = new ArrayList<>();
                for(Object map : data.rows){
                    list.add(new Gson().fromJson(new JSONObject((Map) map).toString(),entityClass));
                }
@@ -56,12 +56,25 @@
            }
        });
    }
    public MutableLiveData<List<D>> getLiveData(){
    public MutableLiveData<ArrayList<D>> getLiveData(){
        return liveData;
    }
    public MutableLiveData getLiveFailed() {
        return liveFailed;
    }
    public class PageHttpObserver extends HttpObserver<PageResult<D>> {
        @Override
        protected void onSuccess(PageResult<D> data) {
            liveData.postValue(data.rows);
        }
        @Override
        protected void onFailed(HttpApiResult httpResult) {
            mActivity.showToast(httpResult.msg);
            liveFailed.postValue(1);
        }
    }
}