Runt
2022-08-13 b3a51f064c4dfb27f54cd9526803338d2e8dc296
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
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.Map;
 
/**
 * 分页
 * Created by Administrator on 2021/11/3 0003.
 */
public abstract class LoadPageViewModel<D> extends BaseViewModel {
 
    public final int SIZE = 10;
    private MutableLiveData<ArrayList<D>> liveData = new MutableLiveData<>();
    private MutableLiveData liveFailed = new MutableLiveData();
 
    /**
     * 请求地址
     * @return
     */
    protected abstract String requestUrl();
 
    /**
     * 数据请求
     * @param page  页数
     * @param 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) {
                //数据转换
                ArrayList<D> list = new ArrayList<>();
                for(Object map : data.rows){
                    list.add(new Gson().fromJson(new JSONObject((Map) map).toString(),entityClass));
                }
                liveData.postValue(list);
            }
 
            @Override
            protected void onFailed(HttpApiResult httpResult) {
                mActivity.showToast(httpResult.msg);
                liveFailed.postValue(1);
            }
        });
    }
    public MutableLiveData<ArrayList<D>> getLiveData(){
        return liveData;
    }
 
    public MutableLiveData getLiveFailed() {
        return liveFailed;
    }
 
}