The basic structure of Java Extension Library Rxjava and its Application scenario summary _java

Source: Internet
Author: User

Basic structure

Let's take a look at some of the most basic code to analyze how this code is implemented in Rxjava.

observable.onsubscribe<string> onSubscriber1 = new observable.onsubscribe<string> () {
  @Override Public
  void Call (subscriber<. Super string> subscriber) {
    subscriber.onnext ("1");
    Subscriber.oncompleted ();
  }
;
subscriber<string> subscriber1 = new subscriber<string> () {
  @Override public
  void oncompleted () {

  }

  @Override public
  void OnError (Throwable e) {

  }

  @Override public
  void OnNext (String s) {

  }
};

Observable.create (OnSubscriber1)
    . Subscribe (SUBSCRIBER1);

First, let's take a look at Observable.create's code.

Public final static <T> observable<t> create (onsubscribe<t> f) {return
  new observable<t> ( Hook.oncreate (f));

Protected observable (onsubscribe<t> f) {
  this.onsubscribe = f;
}

The direct call to the observable constructor is to create a new observable object that we temporarily mark as Observable1 to trace back.
At the same time, we'll keep our incoming Onsubscribe object onSubscribe1 in the Observable1 onsubscribe attribute, which is important in the context that follows.

Next let's look at the subscribe method.

Public final Subscription Subscribe (subscriber<. Super t> subscriber) {return
  observable.subscribe ( Subscriber, this);
}

private static <T> Subscription subscribe (subscriber< Super t> Subscriber, observable<t> observable) {
  ...
  Subscriber.onstart ();
  Hook.onsubscribestart (observable, observable.onsubscribe). Call (subscriber);
  Return Hook.onsubscribereturn (subscriber);
}

As you can see, after subscribe, you call the Observable1.onSubscribe.call method directly, which is called method of the OnSubscribe1 object in our code.
, the incoming parameter is the Subscriber1 object defined in our code. What is done in the call method is to invoke the OnNext and OnComplete methods of the incoming Subscriber1 object.
Is it easy to realize the communication between the observer and the observer?

public void Call (SUBSCRIBER<. Super string> subscriber) {
  subscriber.onnext ("1");
  Subscriber.oncompleted ();
}

Summary of Rxjava usage scenarios

1. Check the cached scene before taking the data
take the data, first check to see if the memory has a cache
Then check the file cache for
Finally, take it from the network
If any one of the preceding conditions is satisfied, the following is not performed

 final observable<string> memory = observable.create (New observable.onsubscribe< String> () {@Override public void call (SUBSCRIBER<. Super string> Subscriber) {if (memorycache!= null)
    {Subscriber.onnext (memorycache);
    else {subscriber.oncompleted ();
}
  }
}); observable<string> disk = Observable.create (new observable.onsubscribe<string> () {@Override public void C
    All (subscriber<!? Super string> Subscriber) {String cachepref = rxpreferences.getstring ("cache"). get (); if (!
    Textutils.isempty (Cachepref)) {subscriber.onnext (cachepref);
    else {subscriber.oncompleted ();

}
  }
});

observable<string> network = observable.just ("network"); The main thing is to rely on concat operator to realize Observable.concat (memory, disk, network). The primary (). Subscribeon (Schedulers.newthread ()).
  Subscribe (s-> {memorycache = "memory"; SYSTEM.OUT.PRINTLN ("--------------Subscribe:" + s);}); 

2. The interface needs to wait for multiple interfaces to fetch the data, and then update

Stitching two observable output, not guaranteed order, is sent to subscriber
private void Testmerge () {
  observable<string> observable1 in the order in which the event is generated Demoutils.createobservable1 (). Subscribeon (Schedulers.newthread ());
  observable<string> observable2 = Demoutils.createobservable2 (). Subscribeon (Schedulers.newthread ());

  Observable.merge (Observable1, Observable2)
      . Subscribeon (Schedulers.newthread ())
      . Subscribe (System.out:: println);
}

3. The request of one interface relies on the data returned by another API request

For example, we often get a list of messages based on the token we have when we need to log in.

Here with Rxjava mainly solve the problem of nested callback, there is a proper noun called callback hell

Networkservice.gettoken ("username", "password")
  . Flatmap (S-> networkservice.getmessage (s))
  . Subscribe (s-> {
    System.out.println ("message:" + s);
  });

4. Interface buttons need to prevent continuous click of the situation

Rxview.clicks (Findviewbyid (r.id.btn_throttle))
  . Throttlefirst (1, timeunit.seconds)
  . Subscribe (Avoid- > {
    System.out.println ("click");
  });

5. Response-style interface

For example, check a checkbox to automatically update the corresponding preference

Sharedpreferences preferences = Preferencemanager.getdefaultsharedpreferences (this);
Rxsharedpreferences rxpreferences = rxsharedpreferences.create (preferences);

Preference<boolean> checked = Rxpreferences.getboolean ("Checked", true);

CheckBox checkbox = (checkbox) Findviewbyid (r.id.cb_test);
Rxcompoundbutton.checkedchanges (CheckBox)
    . Subscribe (checked.asaction ());

6. Complex Data transformations

Observable.just ("1", "2", "2", "3", "4", "5")
  . Map (Integer::p arseint)
  . Filter (s-> s > 1)
  . DISTINCT ()
  . Take (3)
  . Reduce ((integer, Integer2)-> integer.intvalue () + integer2.intvalue ())
  . Subscribe ( System.out::p rintln);//9

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.