Use of the "Android-frame" Rxjava

Source: Internet
Author: User
Tags throwable

Rxjava is the newest and most commonly used, and one of the most favorite frameworks for the program's members.

The core of Rxjava consists of observable (the observer, the source of the event) and Subscriber (The observer), observable is responsible for issuing a series of events, subscriber handling these events.

A observble can issue 0 or more events until the end or error occurs. Each occurrence of an event invokes the OnNext () method of all the observers associated with it, and if it goes wrong, it subscriber The Observer's onerror () method; After the event is published to all observers, the last observer's oncompleted () is recalled Method.

Rxjava is much like the Observer pattern in design mode, but there is a difference that the observer does not emit any events when an observer does not have any observers associated with it.

To use Rxjava in Android, you need to first import the dependencies of Rxjava and rxandroid:

    Compile ' io.reactivex:rxjava:1.2.2    ' io.reactivex:rxandroid:1.2.1 '

DEMO 1:

observable<string> Observabele = Observable.create (NewObservable.onsubscribe<string>() {@Override Public voidCall (SUBSCRIBER&LT;?SuperString>subscriber) {Subscriber.onnext ("Hello RxJava");            Subscriber.oncompleted ();        }        }); Observer<String> Observer =NewObserver<string>() {@Override Public voidoncompleted () {System.out.println ("-------------------->>>>completed"); } @Override Public voidOnError (Throwable e) {} @Override Public voidOnNext (String s) {System.out.println ("------------onNext---------->>>>>>>" +s);        }        }; OBSERVABELE.SUBSCRIBE (Observer);

Create a custom observable observer by using the Create () method of the observable, in the Onsubscribe inner class passed into the parameter by calling OnNext (), OnError () of the Subscriber object parameter of the child method, OnCompleted () Three methods that manipulate all observers bound to the observer.

Using the new Observer () method to create an observer, you need to implement the OnNext (), OnError (), oncompleted () three methods.

By binding an observer with the subscribe () method of the Observeable object, the observer can then receive messages sent by the observer.

DEMO2:

observable<string> Observable = Observable.just ("Hello RxJava", "My", "Name"); Action1<String> next =NewAction1<string>() {@Override Public voidCall (String s) {//code executed in OnNext ()            }        }; Action1<Throwable> error =NewAction1<throwable>() {@Override Public voidCall (Throwable throwable) {//code executed in OnError ()            }        }; Action0 completed=NewAction0 () {@Override Public voidCall () {//code executed in oncompleted ()            }        }; Observable.subscribe (Next, error, completed);

The three sub-methods in subscriber can be split into two Action1 and one Action0. The action1,oncompleted () method corresponding to the OnNext () and OnError () Two methods corresponds to the Action0.

The subscribe () method of the observable object can pass in three action objects, which means that the observer is already bound to an observer, which is made up of these three action. The subscribe () method has multiple overloads, can have only one onnext () method of Action1, can have a OnNext () method Action1 and a OnError () method, or it can have three actions like the code above.

The Just () method of the observable object can have any parameter, which means that the objects are sent one by one through the OnNext () method.

DEMO3:

String[] Array = {"Hello RxJava", "My", "Name"}; Observable<String> observable =Observable.from (array); Action1<String> next =NewAction1<string>() {@Override Public voidCall (String s) {//code executed in OnNext ()System.out.println ("----------------------->>>>>>>>>>" +s);        }        }; Action1<Throwable> error =NewAction1<throwable>() {@Override Public voidCall (Throwable throwable) {//code executed in OnError ()            }        }; Action0 completed=NewAction0 () {@Override Public voidCall () {//code executed in oncompleted ()            }        }; Observable.subscribe (Next, error, completed);

The effect of the Observable.from () method and the Observable.just () method is the same as sending a set of data one after the other, except that the From () method sends data from one array to another, and just () The method is to send the data in each parameter individually.

DEMO4:

Observable<string> Observable =Observable. Just ("Hello RxJava", "AAAA", "bbbbb", "AAAAAACCCC"). Map (NewFunc1<string, string>() {@Override Publicstring Call (String s) {return"string=========" +s;        }                }); Action1<String> next =NewAction1<string>() {@Override Public voidCall (String s) {//code executed in OnNext ()System.out.println ("----------------------->>>>>>>>>>" +s);        }        }; Action1<Throwable> error =NewAction1<throwable>() {@Override Public voidCall (Throwable throwable) {//code executed in OnError ()            }        }; Action0 completed=NewAction0 () {@Override Public voidCall () {//code executed in oncompleted ()            }        }; Observable.subscribe (Next, error, completed);

The map method is to further process the data in the just, for example, the above code is preceded by a string at the other end of each string.

DEMO5:

Observable.just ("Https://api.github.com/users/basil2style"). Map (NewFunc1<string, string>() {@Override Publicstring Call (String s) {StringBuffer result=NULL; Try{URL URL=NewURL (s); HttpURLConnection Connection=(HttpURLConnection) url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setdoinput (true);                            Connection.connect (); intResponsecode =Connection.getresponsecode (); if(Responsecode = = 200) {result=NewStringBuffer (); Bufferedinputstream bis=NewBufferedinputstream (Connection.getinputstream ()); byte[] B =New byte[1024]; intLen =-1;  while(len = Bis.read (b))! =-1) {result.append (NewString (b, 0, Len));                            } bis.close (); }                        } Catch(malformedurlexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); } System.out.println ("------------------->>>>>" +result.tostring ()); returnresult.tostring (); }}). map (NewFunc1<string, infodata>() {@Override PublicInfodata Call (String s) {infodata infodata=NewInfodata (); Try{Jsonobject Object=NewJsonobject (s); Infodata.setid (Object.getint ("id")); Infodata.seturl (Object.getstring ("url")); Infodata.settype (Object.getstring ("Type")); Infodata.setname (Object.getstring ("Name")); } Catch(jsonexception e) {e.printstacktrace (); }                        returnInfodata;                 }}). Subscribeon (Schedulers.io ()). Observeon (Androidschedulers.mainthread ()) . Subscribe (NewObserver<infodata>() {@Override Public voidoncompleted () {System.out.println ("---------------------->>>>>>completed"); } @Override Public voidOnError (Throwable e) {toast.maketext (mainactivity. This, "Failed to get network data", Toast.length_short). Show (); } @Override Public voidOnNext (Infodata infodata) {toast.maketext (mainactivity. This, Infodata.getname (), Toast.length_short). Show (); }                });

This is the use of Rxjava in conjunction with the native Java API to complete the network access code, through the map () method to convert between different parameters, and finally get the Infodata object and output data.

Developers now prefer to use Rxjava and retrofit in conjunction because Rxjava can set up a thread of code execution so that the easy, decoupled substitution of handler and Asynctask for asynchronous data access.

For Rxjava and retrofit use cases I will write in my next post, please look forward to ~ ~

Use of the "Android-frame" Rxjava

Related Article

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.