Rxjava Simple Introduction

Source: Internet
Author: User
Tags error handling throwable

I. Extended Observer pattern

The asynchronous implementation of RxJava is achieved through an extended observer pattern.
Observer mode before writing a series of blogs, you can read:
http://blog.csdn.net/a910626/article/details/50766019
The release subscription model implementation diagram in RX:

Observable and subscriber can do anything, your observable can be a database query, subscriber get the query results and display it on the screen. Your observable can be a click on the screen, subscriber respond to the event and do the processing. Your observable can request data from the Web and subscriber it on the interface, a universal framework that can handle everything.

Two. Advantages of Rxjava

Clear, simple, and more consistent with human thinking, especially with lambda expressions.
Functional style, aspect of creating event flow and data flow
Asynchronous error handling mechanism: The traditional try Cach has no way to handle asynchronous computations, and Rx provides the appropriate error handling mechanism
Easy to use concurrency

Three. Rxjava Application Scenario

Rxbinding throttling (prevents repeated clicks of the button)
Polling
Timed operation
Rxpermissions
Rxbus
Rxjava and retrofit to handle network requests
Instead of listening/observing models
Thread management, providing thread pooling, threading switching (schedulers)
Resolving nested callbacks (FLATMAP)
Provide time delay, timer processing (interval)

Four. How to learn Rxjava

The main components of responsive programming are observable, operator, and subscriber. The flow of information in general-responsive programming is as follows:
Observable->operator1->operator2->operator3->subscriber
In other words, observable is the producer of events, and Subscriber is the ultimate consumer of events.
Because subscriber is typically executed in the main thread, the design requires its code to be as simple as possible, to respond only to events (no changes to events or data), and to modify the events to be done by operator.

Observable produces data, in the middle through several operator, the operator, which is used to transform the data. Eventually he will send subscribers to Subscriber. That is to say, observable is the event's creator, subscriber is the consumer of the event.

Observable is responsible for generating data, subscriber responsible for consumption data.
The operator in the middle is responsible for data conversion.

Be proficient in the use of projects.

Five. Class diagram

1. There are 4 main characters in Rxjava:

? Observable
? Subject
? Observer
? Subscriber
Observable and subject are two "production" entities, and observer and Subscriber are two "consumption" entities. The explicit point observable corresponds to the observer in the observer pattern, while the observer and subscriber correspond to the observer in the Observer pattern. Subscriber is actually a realization of the observer of the abstract class, the later we analyze the source of the time will also be introduced. Subject is more complex and later analyzed.

2.Rxjava Event callback method (actually corresponds to the Observer's Update method)

Unlike the traditional observer pattern, the RxJava event callback method defines two special events: OnCompleted () and OnError (), in addition to the normal event OnNext () (equivalent to OnClick ()/OnEvent ()).
? OnCompleted (): Event queue end. RxJava not only handles each event separately, but also considers them as a queue. RxJava requires that the oncompleted () method be triggered as a flag when no new OnNext () is emitted.
? OnError (): Event queue exception. When an exception occurs during the event processing, the OnError () is triggered and the queue is automatically terminated, and no more events are allowed to be emitted.
? In a properly-run sequence of events, oncompleted () and OnError () have only one, and are the last in the sequence of events. It is important to note that both oncompleted () and OnError () are mutually exclusive, that is, one is called in the queue and no other should be called.

3.action1 Action0
Action extends Function Public  interface Action0 extends Action {?voidCall ();?} Public  interface Action2<T1, T2> extends Action {?voidCall (T1 t1, T2 T2);?} Public  interface Func0<R> extends Function, callable< R> {?    @Override? R call ();?} function Public  interface Function {??} Public  interface Func1<T, R> extends Function  {? R call (T t);?}

Simply explain the Action1 and Action0 that appear in this piece of code. Action0 is an interface of RxJava, it has only one method call (), this method is no parameter no return value, because the OnCompleted () method is also no parameter and no return value, so Action0 can be treated as a wrapper object, will OnCompleted () The content is packaged to pass itself as a parameter to subscribe () to implement an incomplete defined callback. This can actually be seen as passing the oncompleted () method as a parameter into the subscribe (), which is equivalent to "closures" in some other languages. Action1 is also an interface, it also has only one method call (t param), this method also has no return value, but has a parameter; As with Action0, because OnNext (T obj) and onError (Throwable error) are also single parameter no return Value, so Action1 can package OnNext (obj) and onError (error) into subscribe () to implement an incomplete defined callback. In fact, although Action0 and Action1 are most widely used in the API, RxJava is provided with multiple ActionX forms of interfaces (such as Action2, Action3), which can be used to wrap different methods without return values.

4.Subscriber vs Observer

SUBSCRIBER = Observer + subcription
Subscriber, it's almost exactly the same as the Observer interface, just two more ways
OnStart (): It will be called at the beginning of subscribe and before the event is sent, and can be used to do some preparatory work, such as clearing 0 or resetting the data. This is an optional method, and by default its implementation is empty. It is important to note that if the line threads requirements for the preparation work (such as a dialog box that shows progress, which must be performed on the main thread), OnStart () does not apply because it is always called on the thread that occurs in the subscribe and cannot be specified by the thread.
Unsubscribe (): Used to unsubscribe. After this method is called, Subscriber will no longer receive events. In general, before this method is called, you can use isunsubscribed () to determine the state first. To avoid the occurrence of a memory leak, call unsubscribe () in the appropriate place, such as OnPause () OnStop (), as soon as you are no longer in use, to dereference the reference relationship.
Although there are two more methods, but the basic implementation is the same as the observer, so temporarily can not consider the difference between the two. However, it is worth noting that:
In essence, in the process of RxJava subscribe, Observer is always first converted into a subscriber and then used.

5. Line Program Control system

In Rxjava, Scheduler is equivalent to a thread controller, which can be used to specify the thread that each piece of code runs.
Rxjava has built-in several scheduler, the following is a summary:
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, and so on). 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 thread, specifies that the operation runs on the main thread.
So how do we switch threads? There are two methods available in Rxjava: Subscribeon () and Observeon (), and the difference between the two is:
Subscribeon (): Specifies the thread that occurs for the subscribe () subscription, that is, call () execution. Or an event-generated thread. (Specifies the thread to be executed by the observer)
Observeon (): Specifies the thread that the observer is running on, that is, OnNext () execution. Or a thread called event consumption. (Make the thread that the Observer executes)

Six. Get a chestnut.
observable<string> myobservable = Observable.create (NewObservable.onsubscribe<string> () {@Override           Public void Pager(SUBSCRIBER&LT;?SuperString> Sub) {//sub is the Observer, sending a stringSub.onnext ("Hello, world!.");          Sub.oncompleted (); }      }  ); Subscriber<string> Mysubscriber =NewSubscriber<string> () {@Override       Public void OnNext(String s) {System.out.println (s);}@Override       Public void oncompleted() { }@Override       Public void OnError(Throwable e) {}};myobservable.subscribe (Mysubscriber);

blog.csdn.net/qq122627018/article/details/51355871

Rxjava Simple Introduction

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.