Why use the Requestfuture encapsulation Rxjava in volley to handle synchronous requests with asynchronous requests?

Source: Internet
Author: User
Tags call back set time

A few days ago, my brother called me to study Rvjava, in the network request, more concise and more organized, and then will take the time to study, and now the Project network library is volley, on the combination of projects and online demo, suddenly the head jumps out of this problem, it seems that the problem has a little stupid.

Firstly, the noun explains.

volley is Google's father to us encapsulated the network request library, to help us encapsulate the specific request, thread switching and data transformation, suitable for a short number of concurrent network requests.

Volley two classes to be used mainly:requestqueue and Request.

The two most basic request implementations Jsonobjectrequest and Stringrequest are requests that are different from the "token" of the request, and all HTTP requests are created by this class. It encapsulates the main parameters for HTTP requests. (This is an asynchronous network request, so there is a callback for response Listener,error Listener)

    1. METHOD Type–get, POST, PUT, DELETE
    2. Url
    3. Request data (HTTP Body)
    4. Successful Response Listener
    5. Error Listener

Requsetqueue: This is a distribution queue that is used to fetch requst and execute in the worker thread, if it is found in the cache, gets the response from the cache, does not get it, and then uploads the result back to the UI thread.

However Volley as a good network request library, it is also possible to complete the synchronization network request, the need to use the class: requestfuture.

(Synchronous request is, for example shout you come over, you don't come over, I keep shouting, do not go (thread is blocked in that), until you come over, call Onresponse, if you exceed my set time has not come over, I call onerror; asynchronous request Yes, I shouted for you to come over, Then I left, as for when to come over I don't care, you come, I will call back onresponse, you do not come, I will callback OnError)

requestfuture Working principle:

    1. Tectonic requestfuture:requestfuture<jsonobject> future = Requestfuture.newfuture ();
    2. When constructing the volley request, the above object is passed into the request; Jsonobjectrequest request=jsonobjectrequest (Request.Method.GET, Url,future,future,.... );
    3. Add request to request queue: Requestmanager.getrequestqueue (). Add (Request);
    4. The Requestfuture.get method is then called, and the method blocks the current thread
    5. The Get method internally calls wait (time), and there is no result in the wait times that throws a timeout exception; (Wait (0) is an indefinite wait)
    6. In the Get wait procedure, if the volley request arrives, the Onresponse method of Requestfuture is called, and the private T Mresult in the object is set; Requestfuture.get () Returns the result, calling Notifyall (), Waking the waiting thread, not blocking.
    7. Note that because the method is blocked, never call the Get method in the UI thread!! So it needs to be blocked in a new thread, which is given to the Rxjava implementation.

RxJava : If you borrow the drop line

What the hell is RxJava?

One word: async .

RxJava's self-introduction on the GitHub homepage is "A library for composing asynchronous and event-based programs using observable sequences for th e java VM "(a library that uses observable sequences on a Java VM to compose an asynchronous, event-based program). This is RxJava, which is a very precise generalization.

However, for beginners, this is too ugly to understand. Because it is a "summary", and beginners need an "introduction."

In fact, the essence of RxJava can be compressed into the word async. On the root, it is a library that implements asynchronous operations, and other attributes are based on this.

RxJava fortunately

In other words, "the same is done asynchronously, why do people use it instead of ready-made asynctask/handler/xxx/...?" 』

One word: concise .

The key point of asynchronous operations is the simplicity of the program, because asynchronous code is often difficult to write and readable when the scheduling process is complicated. Android created AsyncTask and Handler , in fact, is to make the asynchronous code more concise. The advantage of RxJava is simplicity, but its simplicity is unique in that it remains concise as the program logic becomes more complex.

This is the Rxjava feature, specific to the http://gank.io/post/560e15be2dca930e00da1083


Well, the noun explanation is here. To answer the question, why use the Requestfuture encapsulation Rxjava in volley to handle synchronous requests with asynchronous requests?

In other thoughts, why not use the Requestfuture encapsulation Rxjava in volley to handle asynchronous requests with asynchronous requests? Sounds more stupid. Right, asynchronous, open a thread, asynchronous processing and then open a thread, so open two threads, very wasteful right.

Why not use the Requestfuture encapsulation Rxjava in volley to process requests asynchronously with a synchronous request? Rxjava can also be synchronized, and the observer is placed inside a thread by the observer. Before using volley are asynchronous requests, the implementation of the function we want, why also use Rxjava, back to sync? We use the Rxjava because it's asynchronous + orderly, using it.

This is contradiction, so we use the Requestfuture encapsulation Rxjava in volley to process the synchronous request with an asynchronous request.

Rxjava+volley

 Public classRxrequest {/*** Send POST request * *@paramURL *@paramTarget *@param<T> *@return     */     Public Static<T> observable<t> post (String URL, class<?>target) {        returnRequest (URL, target, Request.Method.POST,NewDefaultretrypolicy ()); }    /*** Send POST request * *@paramURL *@paramTarget *@param<T> *@return     */     Public Static<T> observable<t> post (String URL, class<?>target, Retrypolicy retrypolicy) {        returnrequest (URL, target, Request.Method.POST, retrypolicy); }    /*** Send GET request * *@paramURL *@paramTarget *@param<T> *@return     */     Public Static<T> observable<t> get (String URL, class<?>target) {        returnRequest (URL, target, Request.Method.GET,NewDefaultretrypolicy ()); }    /*** Send GET request * *@paramURL *@paramTarget *@param<T> *@return     */     Public Static<T> observable<t> get (String URL, class<?>target, Retrypolicy retrypolicy) {        returnrequest (URL, target, Request.Method.GET, retrypolicy); }     Public Static<T> observable<t> request (String URL, class<?> target,intmethod, Retrypolicy Retrypolicy) {        FinalRequestfuture<t> requestfuture =requestfuture.newfuture (); Finalgsonrequest<t> request =NewGsonrequest<t> (target, method, URL,NULL, Requestfuture, requestfuture);        Request.setretrypolicy (Retrypolicy);        Request.settag (URL); Requestfuture.setrequest (request);//This is for the following requestfuture.iscancelledreturnObservable.create (NewObservable.onsubscribe<t>() {@Override Public voidCall (SUBSCRIBER&LT;?SuperT>subscriber) {                Try {                    //network request processing only after being subscribed toRequestmanager.getrequestqueue (). Add (Request); if(!subscriber.isunsubscribed () &&!requestfuture.iscancelled ()) {Subscriber.onnext (Requestfuture.get ());//block, return result, wake up subscriber.oncompleted                    (); }                } Catch(Exception e) {subscriber.onerror (e); }}). Subscribeon (Schedulers.io ());//Open IO thread, network request}/*** Cancellation Request * *@paramURL*/     Public Static voidCancelFinalString URL) {Requestmanager.getrequestqueue (). Cancelall (NewRequestqueue.requestfilter () {@Override Public BooleanApply (request<?>request) {                returnRequest.gettag (). Equals (URL);    }        }); }}

Activity (or fragment)

Rxrequest.<mymodel>post (URL, MyModel.class)
             . Observeon(androidschedulers. Mainthread())//Viewer in UI thread
. Subscribe (NewSubscriber<mymodel>() {@Override Public voidoncompleted () {LOG.I ("Rxrequest", "oncompleted"); } @Override Public voidOnError (Throwable e) {LOG.E ("Rxrequest", "OnError", E); } @Override Public voidOnNext (MyModel mymodel) {log.i ("Rxrequest", "onnext==>" +MyModel); } });

Why use the Requestfuture encapsulation Rxjava in volley to handle synchronous requests with asynchronous requests?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.