網站首頁 編程語言 正文
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請求數據
RequestViewModel
由RequestViewModelProvider
提供,你需要傳入Retrofit api接口類型;你也可以自定義ViewModel繼承自RequestViewModel
來處理更多業務邏輯;每個RequestViewModel
可以自動管理多個RequestLiveData
,RequestObj
中的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
相關推薦
- 2024-01-06 SpringBoot3集成RocketMQ
- 2022-04-18 設置彈性布局的三列兩側對齊,最后一行樣式的處理
- 2023-04-12 你真的理解C語言qsort函數嗎?帶你深度剖析qsort函數_C 語言
- 2023-10-17 git更換遠端地址
- 2022-10-16 python讀取Windows注冊表的示例代碼_python
- 2022-07-26 golang控制goroutine數量以及獲取處理結果
- 2022-09-25 windows11 下 virtualenv 的 安裝和啟動
- 2023-12-06 Request method ‘PUT‘ not supported
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支