Rx Learning (i)

Source: Internet
Author: User
Tags emit

Rxjava Study Materials:
  
Https://www.gitbook.com/book/yuxingxin/rxjava-essentials-cn/details
  
The following is just a study note, after adding the actual case, now only theoretical summary:
  
Rxjava Language Features:
  
1, easy concurrency to better utilize the server's ability;
  
2, easy to conditional asynchronous execution;
  
3, a better way to avoid callbacks to hell;
  
4, a reactive approach.
  
Rxjava from the Observer pattern:
  
The following three missing features were added:
  
1, the producer can signal notification when no more data is available: oncompleted () event.
  
2, the producer can signal notification when an error occurs: OnError () event.
  
3,rxjavaobservables can be combined rather than nested, thus preventing developers from getting into a callback hell.
  
Four characters in Rxjava:
  
1,observable: Observed, seen
  
2,observer: Viewer
  
3,subscriber: Subscribers
  
4,subjects: Obedience.
  
Observables and subjects are two "production" entities
  
Observers and Subscribers are two "consumer" entities.
  
The observable of Rxjava
  
OnNext (T) retrieving data
  
OnError (throwable) error found
  
OnCompleted () completed
  
Hot observables and cold observables of Rxjava
  
Hot observables: Launches data as soon as it is created, subscribing his observer to receive data from a location in the sequence.
  
Cold observables: Wait until the Observer subscribes to him to launch the data, ensuring that the data sequence is received.

Observale is created in two ways:

1:create

observable.create (New observable.onsubscribe<object>(){@Overridepublic  voidSuper object> subscriber) {}});

2:from: Create observable from a list, array, and emit data

list<integer> items =NewArraylist<integer>(); Items.Add (1); Observable <Integer> observablestring = observable.from (items); Subscription Subscriptionprint= Observablestring.subscribe (NewObserver<integer>() {@Override Public voidoncompleted () {System.out.println ("Observable completed");} @Override Public voidOnError (Throwable e) {System.out.println ("Oh,no! Something wrong happened! ");} @Override Public voidOnNext (Integer Item) {SYSTEM.OUT.PRINTLN ("Item is" +item);});

3,just

The Just () method can pass in one to nine parameters, which emit it in the order of the parameters passed in.

Children

No reason not to emit data and end the operation:

Observable.empty (), Observable.never (), and

Observable.throw ()

Rxjava offers four different types of subject:

Publishsubject

Behaviorsubject: Send Subscribers the latest data object before the subscription, then send the post-subscription data stream;

Replaysubject: Caches all the data subscribed to, and sends the data stream to any observer who subscribes to him;

Asyncsubject: When observable finishes Ansysubject only the last data is published to each observer of the subscribed subscription.

As in development using rxjava,rxandroid:

Gradle dependencies:

Compile ' io.reactivex:rxandroid:1.1.0' io.reactivex:rxjava:1.1.0 '

Other recommended as plugins:

1,lombok:getsettostringequal and other annotation codes

Annotated code for 2,butterknife:findviewbyidonclick code, etc.

3,retrolambda:java8lambda Correlation function

The specific role of Baidu or Google to search

Just is primarily to get the original observable version, migrating existing code on the basis of a new, responsive architecture that can

Can be a useful starting point.

Private voidLoadapps (AppInfo appone,appinfo apptwo,appinfo appthree) mrecyclerview.setvisibility (view.visible); O Bservable.just (appone,apptwo,appthree). Subscribe (NewObserver<appinfo>() {@Override Public voidoncompleted () {mswiperefreshlayout.setrefreshing (false); Toast.maketext (Getactivity (),"Here's the list!"} @Override Public voidOnError (Throwable e) {toast.maketext (Getactivity (),"Something went wrong!"mswiperefreshlayout.setrefreshing (false);} @Override Public voidOnNext (AppInfo AppInfo) {maddedapps.add (AppInfo); Madapter.addapplication (Maddedapps.size ()-1, AppInfo);}); }

Repeat () duplicate data:

Repeat (3): repeat three times data;

Private voidLoadapps (AppInfo appone,appinfo apptwo,appinfo appthree) mrecyclerview.setvisibility (view.visible); O Bservable.just (Appone,apptwo,appthree). Repeat (3). Subscribe (NewObserver<appinfo>() {@Override Public voidoncompleted () {mswiperefreshlayout.setrefreshing (false); Toast.maketext (Getactivity (),"Here's the list!"} @Override Public voidOnError (Throwable e) {toast.maketext (Getactivity (),"Something went wrong!"mswiperefreshlayout.setrefreshing (false);} @Override Public voidOnNext (AppInfo AppInfo) {maddedapps.add (AppInfo); Madapter.addapplication (Maddedapps.size ()-1, AppInfo);}); }

Defer () declares a observable but you want to postpone the creation of this observable until the viewer subscribes

1PrivateObservable<integer>getInt () {returnObservable.create (subscriber, {if(subscriber.isunsubscribed ()) {return;} App.l.debug ("GETINT"); Subscriber.onnext (42); subscriber.oncompleted ();});2Observable<Integer> deferred =Observable.defer ( this :: getInt); 3deferred.subscribe (number, {app.l.debug (number));}); 

Range ()
Do you need to start firing n numbers from a specified number x? You can use range, which starts with 10 and sends 3 numbers:

Observable.range (10,3 ). Subscribe (NewObserver<integer>() {@Override Public voidoncompleted () {Toast.maketext (), getactivity (),"Yeaaah!", Toast.length_long). Show ();} @Override Public voidOnError (Throwable e) {toast.maketext (Getactivity (),"Something went wrong!", Toast.length_short). Show ();} @Override Public voidOnNext (Integer number) {toast.maketext (getactivity (), "I say" +Number  , Toast.length_short). Show ();}});

Interval ()
The interval () function is useful when you need to create a polling program.

Following the toast data every 3 seconds:

Subscription stopmeplease = Observable.interval (3, timeunit.seconds). Subscribe (NewObserver<integer>() {@Override Public voidoncompleted () {Toast.maketext (), getactivity (),"Yeaaah!", Toast.length_long). Show ();} @Override Public voidOnError (Throwable e) {toast.maketext (Getactivity (),"Something went wrong!", Toast.length_short). Show ();} @Override Public voidOnNext (Integer number) {Toast.maketext (Getactivity (),"I say" +Number , Toast.length_short). Show ();}});

Timer ()

If you need a period of time before launching the observable, you can use the timer () like the following example:

Send data after 3 seconds:

Observable.timer (3, timeunit.seconds). Subscribe (new observer<long>() {    @Override      Public void oncompleted () {    }    @Override    publicvoid  onError (Throwable e) {    }    @Override    publicvoid  OnNext (Long number) {        log.d ("RXJAVA", "I say" + number);}    );

How to filter data observables?
  
Rxjava Let's use the filter () method to filter the unwanted values in our observation sequence, filter ((AppInfo)->appinfo.getname (). StartsWith ("C")) is the data that only wants to show the beginning of C.

1, Filter sequence:

Private voidLoadlist (list<appinfo>apps)    {mrecyclerview.setvisibility (view.visible); Observable.from (Apps) . Filter ((appInfo) appinfo.getname (). StartsWith ("C" ) . Subscribe (NewObserver<appinfo>() {@Override Public voidoncompleted () {mswiperefreshlayout.setrefreshing (false); } @Override Public voidOnError (Throwable e) {toast.maketext (Getactivity (),"Something went wrong!"mswiperefreshlayout.setrefreshing (false); } @Override Public voidOnNext (AppInfo AppInfo) {maddedapps.add (AppInfo); Madapter.addapplication (Maddedapps.size ()-1, AppInfo); }    });}

Filter empty data:

. Filter (new func1<appinfo, boolean>() {    @Override    public  Boolean Call ( AppInfo AppInfo) {        returnnull;    }})

Get several data at the beginning or end: Take () or takelast ().
  
Take the first few data;
  
Takelast after several data.
  
The following is the first three data obtained:

Private voidLoadlist (list<appinfo>apps)    {mrecyclerview.setvisibility (view.visible); Observable.from (Apps). Take (3). Subscribe (NewObserver<appinfo>() {@Override Public voidoncompleted () {mswiperefreshlayout.setrefreshing (false); } @Override Public voidOnError (Throwable e) {toast.maketext (Getactivity (),"Something went wrong!"mswiperefreshlayout.setrefreshing (false); } @Override Public voidOnNext (AppInfo AppInfo) {maddedapps.add (AppInfo); Madapter.addapplication (Maddedapps.size ()-1, AppInfo); }    });}

Get the following three data:

Observable.from (Apps). Takelast (3). Subscribe (...);

Data deduplication DISTINCT:

Manufacturing Duplicate data:

observable<appinfo> fullofduplicates = Observable.from (apps)                                       . Take (3)                                       . Repeat (3);

Go weight:

  

fullofduplicates. Distinct (). Subscribe (NewObserver<appinfo>() {@Override Public voidoncompleted () {mswiperefreshlayout.setrefreshing (false); } @Override Public voidOnError (Throwable e) {toast.maketext (Getactivity (),"Something went wrong!"mswiperefreshlayout.setrefreshing (false); } @Override Public voidOnNext (AppInfo AppInfo) {maddedapps.add (AppInfo); Madapter.addapplication (Maddedapps.size ()-1, AppInfo); }});}

Rx Learning (i)

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.