RequestViewModel
Advantages:
- Quickly and conveniently use ViewModel and LiveData to manage data, and automatically use retrofit to make network requests
- No need to care about the creation of LiveData and retroift requests, just focus on the Bean object that updates data by the UI control
- RequestViewMode automatically caches LiveData, and each retrofit API interface reuses one livedata.
Gradle
Add in the project root directory
allprojects { repositories { google() maven { url '' } jcenter() } }
Added to module:
dependencies { implementation ':RequestViewModel:1.0.3' }
use
Interface declaration
RequestViewModel
Internal useretrofit
When making a network request, the framework will manage the creation of retrofit request objects based on the requested annotation words, parameters and return value types; the first step is the basic steps of Retrofit;
public interface RetrofitDataApi { public static final String requestOilprice = "/oilprice/index?key=3c5ee42145c852de4147264f25b858dc"; public static final String baseUrl = ""; //ResponseJsonBean object is a custom server to return json type, which can be a generic type, such as ResponseData<UserInfo> @GET(requestOilprice) Call<ResponseJsonBean> getOliPrice(@Query("prov") String prov); }
Configuration
You need to use additional use when initializing the appRetrofitConfig
Configure your own Retrofit instance or create a Retrofit instance using the default
Method 1:
Use the project's existing retrofit instance:
Retrofit retrofit = new () .baseUrl() .addConverterFactory(()) .client(new () .build()) .build(); (retrofit).init();
Method 2:
Set baseurl, the framework will help you create default retrofit instance
().init();
3. Create a request object in Activity or Fragment
You need to set the request parameters andRequestObj
The GET or POST annotation string passed in the retrofit API interface into the constructor. The parameter order must be maintained andrequestObj
The corresponding API interface parameters of the API annotation are consistent
RequestObj<T>
Generics declare the type returned by the API request,T
Type support itself is a generic type; you will inherit it yourselfRequestLiveData
In the class, the returned data is converted and parsed and posted to the UI
protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); ... ... //Build the request object, set the request API annotations and parameters, set the API return object type and livedata data typeRequestObj<ResponseJsonBean> requestObj = new RequestObj<ResponseJsonBean>() { @Override public Object[] getArgs() { return new Object[]{formatInputArg()}; } }; ... ... }
4. Inherit RequestLiveData and process return data
Here, convert the data type returned by the server to the type required by the UI and passLiveData post()
Data to UI. The first generic parameter is the data type returned by the retrofit request, and the second generic parameter is the data type held by LiveData.
public class OliPriceLiveData extends RequestLiveData<ResponseJsonBean, PriceBean> { @Override public void onLoadSuccess(ResponseJsonBean data) { if (() == 200) { PriceBean priceBean = ().get(0); (200); postValue(priceBean); } else { PriceBean priceBean = new PriceBean(); (()); (()); postValue(priceBean); } } @Override public void onLoadFailed(int code, String msg) { PriceBean priceBean = new PriceBean(); (code); (msg); postValue(priceBean); } }
5. Use RequestViewModel and RequestLiveData to request data
RequestViewModel
Depend onRequestViewModelProvider
Provided, you need to pass in the Retrofit API interface type; you can also customize the ViewModel inherit fromRequestViewModel
to handle more business logic; eachRequestViewModel
Multiple management can be automatically managedRequestLiveData
,RequestObj
The retrofit api annotation string in the Retrofit API determines whether VeiwModel creates a new oneRequestLiveData
Or reuse the old ones.
RequestLiveData
A request will be made at the first creation; if you are using the Google DataBinding framework,RequestLiveData
After receiving data and postValue, the data will be automatically updated to the UI control.
private RequestViewModel requestViewModel; private OliPriceLiveData liveData; protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); ... ... requestViewModel = ().get( this, , ); //Build the request object, set the request API annotations and parameters, set the API return object type and livedata data type RequestObj<ResponseJsonBean> requestObj = new RequestObj<ResponseJsonBean>() { @Override public Object[] getArgs() { return new Object[]{formatInputArg()}; } }; liveData = (requestObj, ); ... ... }
6. Set request parameters and actively request data
You can also useRequestLiveData
The refresh method actively refreshes the data; and usesRequestObj
setArgs()
Method sets new parameters.
(new Object[]{"arg1",1,...}); ();
7. Observe the changes in RequestLvieData data
Same asLiveData
You can also use the observe interface to observe the number of subclassesRequestLiveData
Changes
(this, new Observer<PriceBean>() { @Override public void onChanged(PriceBean priceBean) { if (() != 200) { (, "Request failed code =" + () + " msg = " + () , Toast.LENGTH_SHORT).show(); } else { //Update ui, use dataBinding to automatically update to ui here ("MainActivity", "price bean onchanged " + ()); } } });
8. Log printing
By default, only ERROR logs are printed. After the INFO log is turned on, all API interface method signatures, request parameters, request response codes, and object hash values for processing requests will be printed.
();
I/[RequestViewModel]: TypedRequest[@96f475c] ------>[interface ] (public abstract <> (,)) args{Shanghai,test,} I/[RequestViewModel]: TypedRequest[@96f475c ]onResponse call return s
This is the article about Github’s simple and easy-to-use Android ViewModel Retrofit framework. For more related Android ViewModel Retrofit content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!