日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Github簡單易用的?Android?ViewModel?Retrofit框架_Android

作者:??OCode???? ? 更新時間: 2022-08-10 編程語言

RequestViewModel

優勢:

  • 快捷、方便地使用ViewModel 、LiveData管理數據,自動使用retrofit進行網絡請求
  • 無需關心LiveData和retroift request的創建,只要關注UI 控件更新數據的Bean對象
  • RequestViewMode自動對LiveData進行緩存管理,每個retrofit api接口復用一個livedata

Gradle

項目根目錄下 build.gradle 添加

allprojects {
    repositories {
        google()
        maven { url 'https://jitpack.io' }
        jcenter()
    }
}

module的build.gradle 中添加:

dependencies {
	implementation 'com.github.miaotaoii:RequestViewModel:1.0.3'

}

使用

1.retrofit接口的聲明

RequestViewModel內部使用retrofit進行網絡請求,框架會根據請求的注解字和參數及返回值類型管理retrofit請求對象的創建;第一步是Retrofit的基本步驟;

public interface RetrofitDataApi {
    public static final String requestOilprice = "/oilprice/index?key=3c5ee42145c852de4147264f25b858dc";
    public static final String baseUrl = "http://api.tianapi.com";
    
    //ResponseJsonBean對象是自定義的服務器返回json類型,可以是泛型類型,如 ResponseData<UserInfo>
    @GET(requestOilprice)
    Call<ResponseJsonBean> getOliPrice(@Query("prov") String prov);
}

2.retrofit配置

你需要在初始化app時,額外使用RetrofitConfig配置你自己的Retrofit實例或使用默認創建retrofit實例

方式1:

使用項目已有的retrofit實例:

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RetrofitDataApi.baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .client(new OkHttpClient.Builder()
                        .build())
                .build();
RetrofitConfig.getInstance(retrofit).init();

方式2:

設置baseurl,框架會幫你創建默認的retrofit實例

RetrofitConfig.getInstance(RetrofitDataApi.baseUrl).init();

3.在Activity或Fragment中創建請求對象

你需要設置請求參數,并在RequestObj構造器中傳入retrofit api接口中的的GET或POST注解字符串。參數順序必須保持和requestObj?的api注解對應的api接口參數一致

RequestObj<T>?泛型聲明api請求返回的類型,T類型支持本身為泛型類型; 你將會在你自己繼承RequestLiveData的類中,對返回數據進行轉化解析并post到UI中

protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		... ...
//構建請求對象,設置請求api注解和參數,設置api返回對象類型和livedata數據類型
RequestObj<ResponseJsonBean> requestObj = new RequestObj<ResponseJsonBean>(RetrofitDataApi.requestOilprice) {
            @Override
            public Object[] getArgs() {
                return new Object[]{formatInputArg()};
            }
        };
		... ... 
}

4.繼承RequestLiveData,處理返回數據

在這里將服務器返回的數據類型轉換為UI需要的類型,并通過LiveData post()數據到UI。第一個泛型參數是retrofit請求返回的數據類型,第二個泛型參數是LiveData持有的數據類型。

public class OliPriceLiveData extends RequestLiveData<ResponseJsonBean, PriceBean> {
    @Override
    public void onLoadSuccess(ResponseJsonBean data) {
        if (data.getCode() == 200) {
            PriceBean priceBean = data.getNewslist().get(0);
            priceBean.setCode(200);
            postValue(priceBean);
        } else {
            PriceBean priceBean = new PriceBean();
            priceBean.setCode(data.getCode());
            priceBean.setMsg(data.getMsg());
            postValue(priceBean);
        }
    }
    @Override
    public void onLoadFailed(int code, String msg) {
        PriceBean priceBean = new PriceBean();
        priceBean.setCode(code);
        priceBean.setMsg(msg);
        postValue(priceBean);
    }
}

5.使用RequestViewModel和RequestLiveData請求數據

RequestViewModelRequestViewModelProvider提供,你需要傳入Retrofit api接口類型;你也可以自定義ViewModel繼承自RequestViewModel來處理更多業務邏輯;每個RequestViewModel可以自動管理多個RequestLiveDataRequestObj中的retrofit api注解字符串決定了VeiwModel是否創建新的RequestLiveData或者復用舊的。

RequestLiveData將在首次創建時發出一次請求;如你正在使用google DataBinding框架,在RequestLiveData?接收數據并postValue后,數據將自動更新到UI控件。

private RequestViewModel requestViewModel;
private OliPriceLiveData liveData;

protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	... ...
	requestViewModel = RequestViewModelProvider.getInstance().get(
						    this,
							RetrofitDataApi.class,
	 					    RequestViewModel.class
	 					    ); 
//構建請求對象,設置請求api注解和參數,設置api返回對象類型和livedata數據類型
	RequestObj<ResponseJsonBean> requestObj = new RequestObj<ResponseJsonBean>(RetrofitDataApi.requestOilprice) {
            @Override
            public Object[] getArgs() {
                return new Object[]{formatInputArg()};
            }
        };

	liveData = requestViewModel.getRequestLiveData(requestObj, OliPriceLiveData.class);

	... ... 
}

6.設置請求參數,主動請求數據

你也可以使用RequestLiveData?的refresh 方法主動刷新數據;并使用RequestObj?setArgs()方法設置新的參數。

  requestObj.setArgs(new Object[]{"arg1",1,...});
  liveData.refresh();

7.觀察RequestLvieData數據變化

同樣作為LiveData的子類,你也可以使用observe接口觀察數RequestLiveData據變化

 liveData.observe(this, new Observer<PriceBean>() {
            @Override
            public void onChanged(PriceBean priceBean) {
                if (priceBean.getCode() != 200) {
                    Toast.makeText(MainActivity.this, "請求失敗 code =" + priceBean.getCode() + " msg = " + priceBean.getMsg()
                            , Toast.LENGTH_SHORT).show();
                } else {
                    //更新ui ,此處使用dataBinding 自動更新到ui
                    Log.i("MainActivity", "price bean onchanged " + priceBean.toString());
                }
            }
        });

8.日志打印

默認只打印ERROR日志,INFO日志開啟后將打印所有請求執行的api接口方法簽名、請求參數、請求response code以及處理請求的對象hash值。

RetrofitConfig.setLogLevel(Logger.LogLevel.INFO);
I/[RequestViewModel]: TypedRequest[com.ocode.requestvm.request.TypedRequestImpl@96f475c] ------>[interface com.requestVM.demo.api.RetrofitDataApi]  (public abstract retrofit2.Call<com.requestVM.demo.api.ResponseJsonBean> com.requestVM.demo.api.RetrofitDataApi.getOliPrice(java.lang.String,java.lang.String)) args{上海,test,}
I/[RequestViewModel]: TypedRequest[com.ocode.requestvm.request.TypedRequestImpl@96f475c ]onResponse call return s

原文鏈接:https://juejin.cn/post/7105751395935977503

欄目分類
最近更新