最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時間:2022年06月17日 09:17:04   作者:??OCode????  
這篇文章主要介紹了Github簡單易用的Android?ViewModel?Retrofit框架,RequestViewMode有自動對LiveData進行緩存管理,每個retrofit api接口復(fù)用一個livedata的優(yōu)勢。下文具體詳情,感興趣的小伙伴可以參考一下

RequestViewModel

優(yōu)勢:

  • 快捷、方便地使用ViewModel 、LiveData管理數(shù)據(jù),自動使用retrofit進行網(wǎng)絡(luò)請求
  • 無需關(guān)心LiveData和retroift request的創(chuàng)建,只要關(guān)注UI 控件更新數(shù)據(jù)的Bean對象
  • RequestViewMode自動對LiveData進行緩存管理,每個retrofit api接口復(fù)用一個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內(nèi)部使用retrofit進行網(wǎng)絡(luò)請求,框架會根據(jù)請求的注解字和參數(shù)及返回值類型管理retrofit請求對象的創(chuàng)建;第一步是Retrofit的基本步驟;

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

2.retrofit配置

你需要在初始化app時,額外使用RetrofitConfig配置你自己的Retrofit實例或使用默認創(chuàng)建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:

設(shè)置baseurl,框架會幫你創(chuàng)建默認的retrofit實例

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

3.在Activity或Fragment中創(chuàng)建請求對象

你需要設(shè)置請求參數(shù),并在RequestObj構(gòu)造器中傳入retrofit api接口中的的GET或POST注解字符串。參數(shù)順序必須保持和requestObj 的api注解對應(yīng)的api接口參數(shù)一致

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

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

4.繼承RequestLiveData,處理返回數(shù)據(jù)

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

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請求數(shù)據(jù)

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

RequestLiveData將在首次創(chuàng)建時發(fā)出一次請求;如你正在使用google DataBinding框架,在RequestLiveData 接收數(shù)據(jù)并postValue后,數(shù)據(jù)將自動更新到UI控件。

private RequestViewModel requestViewModel;
private OliPriceLiveData liveData;

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

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

	... ... 
}

6.設(shè)置請求參數(shù),主動請求數(shù)據(jù)

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

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

7.觀察RequestLvieData數(shù)據(jù)變化

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

 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日志開啟后將打印所有請求執(zhí)行的api接口方法簽名、請求參數(shù)、請求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

到此這篇關(guān)于Github簡單易用的 Android ViewModel Retrofit框架的文章就介紹到這了,更多相關(guān) Android ViewModel Retrofit 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

铁岭县| 东阿县| 无锡市| 小金县| 奇台县| 南涧| 和硕县| 化州市| 绍兴市| 滨海县| 汉阴县| 古交市| 确山县| 南澳县| 普洱| 蕉岭县| 陈巴尔虎旗| 阜城县| 金溪县| 合阳县| 社旗县| 图们市| 达日县| 上思县| 张北县| 华安县| 铁岭市| 南澳县| 靖宇县| 乳源| 舟山市| 麦盖提县| 蓝山县| 灌云县| 防城港市| 方山县| 阜康市| 福建省| 蒲江县| 河间市| 科尔|