* A framework that helps to do asynchronous. Similar to Asynctask. But its flexibility and extensibility are far stronger than the former.
* Home: Https://github.com/ReactiveX/RxJava
* Chinese Information:
* Https://github.com/lzyzsd/Awesome-RxJava
* https://www.zhihu.com/question/35511144
Use
* Asynchronous operation
* You can still keep the logic of your code concise while the program logic is unusually complex
* Configuration: Add dependencies:
* compile ' io.reactivex:rxjava:1.1.3 '
* compile ' io.reactivex:rxandroid:1.1.0 '
Basic concepts:
1. The person being observed: Observable
* Role: Decide when to trigger events and what events to trigger
* Method of Creation:
* Observable.just (T ...) parameter is a single
* Observable.from (t[])/Observable.from (iterable<? extends t>) parameter is an array or iterable
2. Viewer: Observer
* Role: What happens when an event is triggered
* Implementation class has Observer/subscriber
3. Subscription: Subscribe
* Role: Linking observable and Observer
Method
* OBSERVABLE.SUBSCRIBE (Observer);
* Observable.subscribe (subscriber);
4. Event:
* OnNext (): Normal event
* oncompleted (): Event queue End
* ONERROR (): Event Queue exception
* It is important to note that oncompleted () and onerror () are mutually exclusive. One of the calls should not trigger the other.
1. Create a Observable object
observable<string> myobservable = observable.create ( new observable.onsubscribe<string> () { @ Override public void Call (SUBSCRIBER<? Super String> Sub) { sub.onnext ("Hello, world!");//Notify Subscribers Sub.oncompleted (); } } );
2. Create a subscriber to handle strings emitted by observable objects
subscriber<string> mysubscriber = new subscriber<string> () { @Override public void OnNext (String s ) {System.out.println (s);} @Override public void oncompleted () {} @Override public void OnError (Throwable e) {}
3. Associate the defined Myobservable object with the Mysubscriber object so that the subscriber subscription to observable is completed.
Myobservable.subscribe (Mysubscriber);
Simplified version:
observable<string> myobservable = Observable.just ("Hello, world!"); action1<string> onnextaction = new action1<string> () { @Override public void Call (String s) { System.out.println (s); } };
Final Simplified version:
Observable.just ("Hello, world!") . Subscribe (new action1<string> () { @Override public void Call (String s) { System.out.println (s); } });
Example code:
1. Existing an array string[] arr ={"AFDSA", "Bfdsa", "CFDA"}, find the string that begins with the letter "a" and add "from Alpha", and finally print out the length of the new string
Observable . From (arr) . Filter (New func1<string, boolean> () { @Override public Boolean Call ( String s) { return S.startswith ("a"); } }) . Map (new func1<string, string> () { @Override public String Call (string s) { return S + ' from Alpha ';
} }) . Subscribe (New action1<string> () { @Override public void Call (String s) { System.out.println ("Rxjava:" + s.length ()); } ); /original Java code for (int i = 0; i < arr.length; i++) { String temp = arr[i]; if (Temp.startswith ("a")) { temp + = "from Alpha"; System.out.println ("Normal:" + temp.length ());} }
Gets a picture from the specified drawable file ID and displays it in ImageView, and prints a Toast error when an exception occurs:
imageview IV = (ImageView) Findviewbyid (R.id.imageview); Observable.just (R.mipmap.ic_launcher). Subscribeon (Schedulers.io ())//run in a child thread. Map (New Func1<inte GER, Drawable> () {@Override public drawable call (Integer integer) {r Eturn getresources (). getdrawable (integer); }}). Observeon (Androidschedulers.mainthread ())//run in the main thread. Subscribe (New Action1<drawa Ble> () {@Override public void call (Drawable drawable) {Iv.setimagedr Awable (drawable); } });}
6. Scheduler
* Function: Control thread. Specifies that a piece of code runs in that thread.
* Built-in scheduler:
* Schedulers.immediate (): Runs directly on the current thread, which is equivalent to not specifying a thread. This is the default Scheduler.
* Schedulers.newthread (): Always enable new threads and perform operations on new threads.
* Schedulers.io (): Scheduler used by I/O operations (read-write files, read-write databases, network information interactions, etc.). The behavior pattern is almost the same as Newthread (), except that the internal implementation of IO () is the use of an unlimited thread pool that can reuse idle threads, so that Io () is more efficient in most cases than Newthread (). Do not put the calculation work in IO (), you can avoid creating unnecessary threads.
* Schedulers.computation (): Calculates the Scheduler used. This calculation refers to CPU-intensive computations, i.e., operations that do not restrict performance by operations such as I/O, such as the calculation of a sample. This Scheduler uses a fixed thread pool with a size of CPU cores. Do not put the I/O operation in computation (), otherwise the wait time of the I/O operation wastes the CPU.
* Androidschedulers.mainthread (): Android dedicated, it specifies that the operation will run on the Android main thread.
* Methods for specifying threads:
* Observable.subscribeon (): Specifies the thread that occurs for subscribe ().
Subscribeon (Schedulers.io ())
* Observable.observeon (): Specifies the thread that the Subscriber is running on.
Observeon (Androidschedulers.mainthread ())
7. Data Transformation:
* Function: To process an object or an entire sequence in a sequence of events into different events or sequence of events
* Observable.map: one-to-one conversion
private void Simpledemo () { Observable . Just (R.mipmap.ic_launcher) . Map (new Func1<integer, drawable > () { @Override public drawable call (Integer integer) { return getresources (). getdrawable (integer); } }) . Subscribe (new action1<drawable> () { @Override public void Call (Drawable drawable) { Imageview.setimagedrawable (drawable);}} ); }
The rxjava/rxandroid of the integrated Open source framework