Immediately after the previous post, this article introduces Rxjava, a library that implements asynchronous operations .
Rxjava's core two things are observables and subscribers.
1.OBSERVABLES (Observer, event source) issues a series of events
2.Subscribers (Viewer) handles these events
The events here can be anything you're interested in (touch events, data returned by web interface calls, etc.)
A observable can issue 0 or more events, knowing the end or error.
Each event is emitted, the OnNext method of its subscriber is called, and the Last Call Subscriber.onnext () or Subscriber.onerror () ends.
Rxjava seems to want to design the observer pattern in the pattern, but there is a clear difference, that is, if a observerble does not have any subscriber, then this observable will not emit any events.
eg. a program that uses Rxjava to print Hello World
1. Create a observable: Call Observable.create
observable<string> myobservable = observable.create ( new observable.onsubscribe< String>() { @Override publicvoidSuper string> sub) { Sub.onnext ("Hello, world!" ); Sub.oncompleted (); } } );
You can also use the simplified version:
observable<string> myobservable = Observable.just ("Hello, world!")
The observable object defined here simply emits a Hello world string and then ends.
2. Create a Subscriber that handles the string emitted by the observable object.
New Subscriber<string>() { @Override publicvoid onNext (String s) { System.out.println (s); } @Override publicvoid oncompleted () {} @Override publicvoid onError (Throwable e) {} };
Simplified version:
New Action1<string>() { @Override publicvoid call (String s) { System.out.println (s); } };
Subscriber is just a string that prints observable.
The 3.subscribe function associates the Myobservable object with the Mysubscriber object. A subscription to observable was completed for subscriber.
Myobservable.subscribe (Mysubscriber);
If the previously used Action1 class, then subscribe using the following method:
Myobservable.subscribe (onnextaction);
The concise version before the composition can be written like this:
Observable.just ("Hello, world!" ) . Subscribe (New action1<string>() { @Override public void Call (String s) { System.out.println (s); } });
4. Complete. Now that Mysubscriber subscribes to Myobservable,myobservable is the OnNext and OnComplete method that calls the Mysubscriber object, Mysubscriber will print out Hello world!
The above is a simple rxjava usage, let's look at how to use Rxjava in Movieguide:
In Movieguide, Rxjava is primarily used in iterator classes
Todo
Android Learning Note (2)--rxjava