SoFunction
Updated on 2025-03-11

Github's simple and easy-to-use Android ViewModel Retrofit framework

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

RequestViewModelInternal useretrofitWhen 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&lt;ResponseJsonBean&gt; getOliPrice(@Query("prov") String prov);
}

Configuration

You need to use additional use when initializing the appRetrofitConfigConfigure 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 andRequestObjThe GET or POST annotation string passed in the retrofit API interface into the constructor. The parameter order must be maintained andrequestObjThe corresponding API interface parameters of the API annotation are consistent

RequestObj<T>Generics declare the type returned by the API request,TType support itself is a generic type; you will inherit it yourselfRequestLiveDataIn 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&lt;ResponseJsonBean&gt; requestObj = new RequestObj&lt;ResponseJsonBean&gt;() {
            @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

RequestViewModelDepend onRequestViewModelProviderProvided, you need to pass in the Retrofit API interface type; you can also customize the ViewModel inherit fromRequestViewModelto handle more business logic; eachRequestViewModelMultiple management can be automatically managedRequestLiveDataRequestObjThe retrofit api annotation string in the Retrofit API determines whether VeiwModel creates a new oneRequestLiveDataOr reuse the old ones.

RequestLiveDataA request will be made at the first creation; if you are using the Google DataBinding framework,RequestLiveDataAfter 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&lt;ResponseJsonBean&gt; requestObj = new RequestObj&lt;ResponseJsonBean&gt;() {
            @Override
            public Object[] getArgs() {
                return new Object[]{formatInputArg()};
            }
        };

	liveData = (requestObj, );

	... ... 
}

6. Set request parameters and actively request data

You can also useRequestLiveDataThe 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 asLiveDataYou can also use the observe interface to observe the number of subclassesRequestLiveDataChanges

 (this, new Observer&lt;PriceBean&gt;() {
            @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] ------&gt;[interface ]  (public abstract &lt;&gt; (,)) 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!