RX Series Four | rxandroid | Loading Pictures | Submit Form

Source: Internet
Author: User

RX Series Four | rxandroid | Loading Pictures | Submit Form

To tell the truth, Learning Rxjava is for us to use in the Android more comfortable, that is, rxandroid, we still step by step, learn how to use the better, the previous three is a cushion, let you have a little understanding, that Rx in Android what is the advantage? Let's start by simulating some primitive functions and comparing them

I. Loading pictures

Many people say that Rx comes out, is the programming idea of an advanced, in fact, I learned this idea, I really feel that there is a great change, but, need a little learning cost plus, need to change the original thought, so I still a little not adapt, do not know why, It may be like a few years of eclipse, suddenly let me use the feeling of Android studio, but the technology in progress, everyone needs to accept, there is no good or bad points, then we explain the RX, we first put the idea, logic to do a cushion it, first, We have to prepare something because it involves the network request, download and other functions, so we must be going to add under Network permissions

<!--网络权限--><uses-permission android:name="android.permission.INTERNET"/>

And then we'll take a look at what we're going to do now, first of all, we'll load a picture, and we'll do it by Asynctask, but it's a long, boring code, and in our activity, In fact, the last activity itself he has a lot of work to do, so that the code will be many, not easy to refactor, and so on, so there will be the current MVC,MVP and other architectures to decouple, so since the RX programming itself is a very concise code, then we should use what method to achieve reasonable? Let's write an analytic method, because we need to use okhttp, so please add in Gradle

  //OkHttp3  ‘com.squareup.okhttp3:okhttp:3.+‘

It's good to load, so let's write a method.

   //Load Picture    Privateobservable<byte[]>lodingimg(String Imgpath) {returnObservable.create (Newobservable.onsubscribe<byte[]> () {@Override             Public void Pager(SUBSCRIBER&LT;?Super byte[]> subscriber) {if(!subscriber.isunsubscribed ()) {//Parse pictureOkhttpclient client =NewOkhttpclient (); Request Request =NewRequest.builder (). URL (imgpath). build (); Client.newcall (Request). Enqueue (NewCallback () {@Override                         Public void onfailure(Call call, IOException e)                        {Subscriber.onerror (e); }@Override                         Public void Onresponse(Call call, Response Response)throwsIOException {if(Response.issuccessful ()) {byte[] bytes = response.body (). bytes ();if(Bytes! =NULL) {Subscriber.onnext (bytes); }                            }//EndSubscriber.oncompleted ();                }                    });    }            }        }); }

This method can see that our return value is a byte array parameter of the Observer observable, and then pass an address, we will go directly back to a observable, in observable, we do what things? In fact, we directly with Okhttp to parse a picture, got a byte, passed through Subscriber.onnext (bytes) to the Observer, let him do the operation, of course, do not forget to call oncompleted to tell the Observer has ended the operation, And on the observer side, what do you need to do?

    @Override     Public void OnClick(View v) {Switch(V.getid ()) { CaseR.id.btn_download:lodingimg (Img_path)//Network access. Observeon (Schedulers.io ())//ui Threads. Observeon (Androidschedulers.mainthread ())//Subscription. Subscribe (Newobserver<byte[]> () {@Override                     Public void oncompleted() {log.i (TAG,"OnCompleted"); }@Override                     Public void OnError(Throwable e)                    {log.i (tag,e.tostring ()); }@Override                     Public void OnNext(byte[] bytes) {Bitmap Bitmap = Bitmapfactory.decodebytearray (Bytes,0, bytes.length);                    Img.setimagebitmap (bitmap); }                }); Break; }    }

In fact, we can see, we directly to subscribe to a subscribe, in OnNext, through the Bitmapfactory method into a bitmap, this is the RX loading process, this way will have a great impact on us, At least now we know a little bit about his routine, so let's take a look at the running results.

OK, and it was a smooth load.

Two. Submitting the form

If the loading picture is get, then the submission form is post, let's look at how to write the submission form, we assume that it is a login registration function, it is very simple, we look at the code we want to do this time

   //Login    PrivateObservable<String>Fromlogin (StringUrlMap<String,String> params){returnObservable.CreateNewObservable.Onsubscribe<String>() {@Override Public voidCall (subscriber<?SuperString>Subscriber) {if(!Subscriber.Isunsubscribed ()) {Okhttpclient Client= NewOkhttpclient (); Formbody.Builder Builder= NewFormbody.Builder ();if(params!=NULL && !params.IsEmpty ()) {for (Map.Entry<String,String>Entryparams.EntrySet ()) {Builder.Add (entry.GetKey (), entry.GetValue ()); }} requestbody Requestbody=Builder.Build ();//Build POST requestRequest Request= NewRequest.Builder ().URL (URL).Post (Requestbody).Build (); Client.Newcall (Request).EnqueueNewCallback () {@Override Public voidOnFailure (call call, IOException e) {subscriber.OnError (e); } @Override Public voidOnresponse (call call, Response Response) throws IOException {if(Response.Issuccessful ()) {Subscriber.OnNext (response.Body ().string()); }//End of VisitSubscriber.OnCompleted ();                }                    });    }            }        }); }

In this code, we can see that we have defined a method, the return value is a string type of the observer observable, and the passed parameter is the address of the login and a map key value pair, we directly return a observable can, Inside we use Okhttp to submit the form, and finally return the result through OnNext, through oncompleted to tell the end of the operation, and what should we do in our observer?

@Override Public voidOnClick (View v) {switch (v.GetId ()) { CaseR.Id.Btn_login:StringName=Et_name.GetText ().ToString ().Trim ();StringPassword=Et_password.GetText ().ToString ().Trim ();if(!Textutils.IsEmpty (name)) {if(!Textutils.IsEmpty (password)) {Map<String,String> params = NewHashMap<>();params.Put"Name", name);params.Put"Password", password); Fromlogin (Login_url,params)//Network access                                .Observeon (schedulers.Io ())//ui Threads                                .Observeon (androidschedulers.Mainthread ()).SubscribeNewObserver<String>() {@Override Public voidOnCompleted () {Log.ITAG,"OnCompleted"); } @Override Public voidOnError (Throwable e) {Log.ITAGE.ToString ()); } @Override Public voidOnNext (Strings) {Log.ITAG, s);                    }                                }); }Else{Toast.Maketext (This,"Password cannot be empty", Toast.Length_short).Show (); }                }Else{Toast.Maketext (This,"Account cannot be empty", Toast.Length_short).Show ();        } break; }    }

In this click event, we can see directly to plug in the parameters after the subscribe subscription to get results, so if the login success jump, this is a set of logic, here no address, do not demonstrate, to here, I believe that everyone on the basic use should be no problem, a word summary, is asynchronous, let our code logic stronger, of course, now the example is not friendly expression of the essence, we are interested can follow the series

Sample download: The last article of the series offers an interesting addition to the group: 555974449

RX Series Four | rxandroid | Loading Pictures | Submit Form

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.