Import Android.util.log;import Rx. Observable;import Rx. Subscriber;import Rx.functions.action1;public class Rxjavademo {private static final String TAG = RXJavaDemo.class.get Simplename (); private int count = 0; Public Rxjavademo () {} public void call () {new Thread (new Runnable () {@Override Publ IC void Run () {while (true) {mobservable.subscribe (msubscriber); Mobservable.subscribe (Action1); Observable.just ("Just Object"). Subscribe (Action1); }}). Start (); } private Observable<string> mobservable = observable.create (New observable.onsubscribe<string> () {@Override public void call (SUBSCRIBER<? Super String> Subscriber) { Subscriber.onnext ("1"); Subscriber.onnext ("2"); Subscriber.onnext ("3"); SubscRiber.oncompleted (); } }); Private subscriber<string> Msubscriber = new subscriber<string> () {@Override public void OnNext (String s) {LOG.V (TAG, "OnNext, String:" + s); LOG.V (TAG, "OnNext, Count:" + count); count++; try {thread.sleep (2000); } catch (Interruptedexception e) {e.printstacktrace (); }} @Override public void oncompleted () {LOG.V (TAG, "oncompleted"); } @Override public void OnError (Throwable e) {log.v (TAG, "OnError, E:" + e.tostring ()); } }; Private action1<string> Action1 = new Action1 () {@Override public void call (Object o) {if (o = = null) {LOG.V (TAG, "Action1, object is null"); Return } log.v (TAG, "Acition1, O:" + (String) o); } };}
Compile ' io.reactivex:rxjava:1.0.9 ' compile ' io.reactivex:rxandroid:0.24.0 ' compile ' com.squareup.retrofit:retrofit:1.9.0 '
Rxjava offers four different types of subject:publishsubject, Behaviorsubject, Replaysubject, Asyncsubject
Behaviorsubject will first send to his subscribers the most recent data object (or initial value) as of the pre-subscription, and then send the subscribed data stream normally.
Replaysubject, it caches all the data it subscribes to and re-sends it to any observer who subscribes to it.
Asyncsubject, when observable is finished, only the last data is published to each observer who has subscribed.
Publishsubject, no data is sent, the observer can only wait, no thread is blocked, no resource is consumed. The message is sent when Publishsubject.onnext is called. After the message is sent, the publishsubject does not end, and the observer waits for the message to be sent again. If you want to close publishsubject,publishsubject you need to call the Publishsubject.oncompleted method off. At this point, the publishsubject sends the message again, and the observer cannot receive the message sent.
Android Development's simple implementation of Rxjava