Error handling of Rxjava

Source: Internet
Author: User
Tags throwable

When observable transmit data, onerror notifications are sometimes sent, causing the observer to not receive data normally. However, there are times when we want to respond to a onerror notification of a observable launch or recover from an error. How do we deal with this at this point? Below we understand the Rxjava error handling related operators.

Catch flowchart

Overview

The catch operator intercepts the ONERROR notification of the original observable and replaces it with other data items or data sequences so that the resulting observable can terminate normally or never terminate at all.

In Rxjava, a catch is implemented as three different operators:

    • Onerrorreturn: Lets observable launch a special item and terminate normally when encountering an error.
    • Onerrorresumenext: Let observable start firing a second observable data sequence when encountering an error.
    • Onexceptionresumenext: Let observable continue to launch the following data item when encountering an error.
Onerrorreturn flowchart

Overview

The Onerrorreturn method creates and returns a new observable that has a similar original observable, which ignores the onerror call of the former and does not pass the error to the Observer, as an alternative, it creates a special item concurrent launch through the parametric function, Finally, the OnCompleted method of the observer is called.

Api
Javadoc: onErrorReturn(Func1))
Sample code
Observable.create (New observable.onsubscribe<student> () {@Override public void call (SUBSCRIBER&LT;? Super Stu        dent> subscriber) {Subscriber.onnext (Getlistofstudent (). Get (0));        Subscriber.onnext (Getlistofstudent (). Get (1));        Subscriber.onnext (Getlistofstudent (). Get (2));        Subscriber.onerror (New Throwable ("Do OnError"));        Subscriber.onnext (Getlistofstudent (). Get (3));        Subscriber.onnext (Getlistofstudent (). Get (4));    Subscriber.onnext (Getlistofstudent (). Get (5));            }}). Subscribeon (Schedulers.io ()). Onerrorreturn (New func1<throwable, student> () {@Override            Public Student Call (Throwable throwable) {return new Student (1001, "Error-1", 10); }}). Observeon (Androidschedulers.mainthread ()). Subscribe (New subscriber<student> () {@Over                Ride public void OnStart () {Super.onstart ();         Madastudent.clear ();   } @Override public void oncompleted () {log.i (TAG, "do oncompleted");            } @Override public void OnError (Throwable e) {log.i (TAG, "do OnError");                } @Override public void OnNext (Student Student) {log.i (TAG, "do OnNext");            Madastudent.adddata (student); }        });
Log Print
OperateActivity: do onNextStudent{id=‘1‘name=‘A‘, age=23}OperateActivity: do onNextStudent{id=‘2‘name=‘B‘, age=33}OperateActivity: do onNextStudent{id=‘3‘name=‘C‘, age=24}OperateActivity: do onNextStudent{id=‘1001‘name=‘error - 1 ‘, age=10}OperateActivity: do onCompleted
Example parsing

When Observale is manually created, when observable sends the third data, observable sends a ONERROR notification and then sends 2 data. In the Onerrorreturn method process, the parameter function creates and returns a special item (New Student (1001, "Error-1", 10)).

As can be seen from log printing, the Observer did not execute the OnError method, meaning that Observale did not receive a ONERROR notification, but instead received a special item, called the OnCompleted method, and ended the subscription. This special item is the special item that is created in the Onerrorreturn parameter function.

Onerrorresumenext flowchart

Overview

The Onerrorresumenext method creates and returns a new observable that has a similar original observable, which ignores the onerror call of the former and does not pass the ONERROR notification to the observer, but as an alternative, = The new observable starts firing data.

The Onerrorresumenext method is similar to the Onerrorreturn () method, which is to intercept the ONERROR notification of the original observable, unlike the post-interception process, Onerrorreturn creates and returns a special item, While Onerrorresumenext creates and returns a new OBSERVABL, the observer subscribes to it and receives the data it emits.

Api
Javadoc: onErrorResumeNext(Func1))Javadoc: onErrorResumeNext(Observable))
Sample code
Observable.create (New observable.onsubscribe<student> () {@Override public void call (SUBSCRIBER&LT;? Super Stu        dent> subscriber) {Subscriber.onnext (Getlistofstudent (). Get (0));        Subscriber.onnext (Getlistofstudent (). Get (1));        Subscriber.onnext (Getlistofstudent (). Get (2));        Subscriber.onerror (New Throwable ("Do OnError"));        Subscriber.onnext (Getlistofstudent (). Get (3));        Subscriber.onnext (Getlistofstudent (). Get (4));    Subscriber.onnext (Getlistofstudent (). Get (5));            }}). Subscribeon (Schedulers.io ()). Onerrorresumenext (New func1<throwable, observable<student>> () { @Override Public observable<student> Call (Throwable throwable) {return OBSERVABLE.J            UST (New Student (1001, "Error-1", "ten"), New Student (1002, "Error-2", 10)); }}). Observeon (Androidschedulers.mainthread ()). Subscribe (New subscriber<student> () {@Over Ride Public void OnStart () {Super.onstart ();            Madastudent.clear ();            } @Override public void oncompleted () {log.i (TAG, "do oncompleted");            } @Override public void OnError (Throwable e) {log.i (TAG, "do OnError");                } @Override public void OnNext (Student Student) {log.i (TAG, "do OnNext");                LOG.I (TAG, student.tostring ());            Madastudent.adddata (student); }            });
Log Print
OperateActivity: do onNextStudent{id=‘1‘name=‘A‘, age=23}OperateActivity: do onNextStudent{id=‘2‘name=‘B‘, age=33}OperateActivity: do onNextStudent{id=‘3‘name=‘C‘, age=24}OperateActivity: do onNextStudent{id=‘1001‘name=‘error - 1 ‘, age=10}OperateActivity: do onNextStudent{id=‘1002‘name=‘error - 2 ‘, age=10}OperateActivity: do onCompleted
Example parsing

When Observale is manually created, when observable sends the third data, observable sends a ONERROR notification and then sends 2 data. In the parameter function in the Onerrorresumenext method, a new observable is created.

As can be seen from log printing, the Observer did not execute the OnError method, meaning that Observale did not receive the ONERROR notification, but instead received the new creation of a new observable launch. After the new observable launches the data, the OnCompleted method is called and the subscription is ended.

Onexceptionresumenext flowchart

Overview

The Onexceptionresumenext method is similar to the Onerrorresumenext method to create and return a new observable that has a similar original observable, and also uses this alternate observable. The difference is that if onerror receives a throwable that is not a exception, it passes the error to the Observer's OnError method and does not use an alternate observable.

Api
Javadoc: onExceptionResumeNext(Observable))
Sample code
Observable.create (New observable.onsubscribe<student> () {@Override public void call (SUBSCRIBER&LT;? Super Stu        dent> subscriber) {Subscriber.onnext (Getlistofstudent (). Get (0));        Subscriber.onnext (Getlistofstudent (). Get (1));        Subscriber.onnext (Getlistofstudent (). Get (2));        Subscriber.onerror (New Throwable ("Do OnError"));        Subscriber.onnext (Getlistofstudent (). Get (3));        Subscriber.onnext (Getlistofstudent (). Get (4));    Subscriber.onnext (Getlistofstudent (). Get (5));                }}). Subscribeon (Schedulers.io ()). Onexceptionresumenext (Observable.just (New Student (1001, "Error-1", 10), New Student (1002, "Error-2", Ten)). Observeon (Androidschedulers.mainthread ()). Subscribe (New Sub                Scriber<student> () {@Override public void OnStart () {Super.onstart ();            Madastudent.clear ();           } @Override public void oncompleted () {     LOG.I (TAG, "do oncompleted");            } @Override public void OnError (Throwable e) {log.i (TAG, "do OnError");                } @Override public void OnNext (Student Student) {log.i (TAG, "do OnNext");                LOG.I (TAG, student.tostring ());            Madastudent.adddata (student); }        }); Observable.create (New observable.onsubscribe<student> () {@Override public void call (SUBSCRIBER&LT;? s            Uper student> subscriber) {Subscriber.onnext (Getlistofstudent (). Get (0));            Subscriber.onnext (Getlistofstudent (). Get (1));            Subscriber.onnext (Getlistofstudent (). Get (2));            Subscriber.onerror (New Exception ("Do OnError"));            Subscriber.onnext (Getlistofstudent (). Get (3));            Subscriber.onnext (Getlistofstudent (). Get (4));        Subscriber.onnext (Getlistofstudent (). Get (5)); }    }) ***
Log Print
1.do onError  2.OperateActivity: do onNextStudent{id=‘1‘name=‘A‘, age=23}OperateActivity: do onNextStudent{id=‘2‘name=‘B‘, age=33}OperateActivity: do onNextStudent{id=‘3‘name=‘C‘, age=24}OperateActivity: do onNextStudent{id=‘1001‘name=‘error - 1 ‘, age=10}OperateActivity: do onNextStudent{id=‘1002‘name=‘error - 2 ‘, age=10}OperateActivity: do onCompleted
Example parsing

When creating Observale to send onerror notifications, error takes two ways, one is throwable and the other is exception. As can be seen from the printed log, when the first method is used, the original observable sends the ONERROR notification directly and ends the launch. However, with the launch exception as the ONERROR notification, the ONERROR notification of the original Observale is intercepted, and the Onexceptionresumenext () is used to create the standby observale. As described in the overview, the Onexceptionresumenext method intercepts the exception as onerror in the original Observale and emits data from the alternate observable created in the parameter function.

Retry flowchart

Overview

The retry () operator will intercept the original observable pass onerror to the Observer, but re-subscribe to the observable. Duplication of data is caused by re-subscribing.

In Rxjava, there are several variants of the retry () operator

The retry () variant will have unlimited re-subscribing to the original observable when a onerror notification occurs.

The retry (long) variant specifies the maximum number of re-subscriptions by parameter, and if the number of times is too high, it will not attempt to subscribe again, it will pass the latest one ONERROR notification to its observer.

The retry (FUNC2) variant takes a function of two parameters by parameter, the parameter is retried and the throwable that causes the emission onerror notification, and the function returns a Boolean value, if the return true,retry should subscribe to the original observable again, If returned False,retry will pass the latest one ONERROR notification to its observer.

Api
Javadoc: retry()Javadoc: retry(long)Javadoc: retry(Func2)
Sample code
Observable.create (New observable.onsubscribe<student> () {@Override public void call (SUBSCRIBER&LT;? Super Stu        dent> subscriber) {Subscriber.onnext (Getlistofstudent (). Get (0));        Subscriber.onnext (Getlistofstudent (). Get (1));        Subscriber.onnext (Getlistofstudent (). Get (2));            if (isError) {subscriber.onerror (new Throwable ("Do OnError"));        IsError = false;        } subscriber.onnext (Getlistofstudent (). Get (3));        Subscriber.onnext (Getlistofstudent (). Get (4));    Subscriber.onnext (Getlistofstudent (). Get (5)); }}). Retry (3). Subscribeon (Schedulers.io ()). Observeon (Androidschedulers.mainthread ()). Subscribe (NEW                Subscriber<student> () {@Override public void OnStart () {Super.onstart ();            Madastudent.clear ();            } @Override public void oncompleted () {log.i (TAG, "do oncompleted");         }   @Override public void OnError (Throwable e) {log.i (TAG, "do OnError");                } @Override public void OnNext (Student Student) {log.i (TAG, "do OnNext");                LOG.I (TAG, student.tostring ());            Madastudent.adddata (student); }        });
Log Print
OperateActivity: do onNextStudent{id=‘1‘name=‘A‘, age=23}OperateActivity: do onNextStudent{id=‘2‘name=‘B‘, age=33}OperateActivity: do onNextStudent{id=‘3‘name=‘C‘, age=24}OperateActivity: do onNextStudent{id=‘1‘name=‘A‘, age=23}OperateActivity: do onNextStudent{id=‘2‘name=‘B‘, age=33}OperateActivity: do onNextStudent{id=‘3‘name=‘C‘, age=24}OperateActivity: do onNextStudent{id=‘4‘name=‘D‘, age=24}OperateActivity: do onNextStudent{id=‘5‘name=‘E‘, age=33}OperateActivity: do onNextStudent{id=‘6‘name=‘F‘, age=23}
Example parsing

As you can see from the sample code, the first time you subscribe, you send a ONERROR notification after the third notification is launched. However, through the log printing can be clearly seen that the ONERROR notification is not launched, but re-subscribed to the data before the launch, re-sent again. As previously stated, the retry () operator intercepts onerror notifications and re-subscribes, but it causes duplication of data.

Retrywhen flowchart

Overview

Retrywhen () is executed by default on the trampoline scheduler, and other schedulers can be specified by parameters.

Api
Javadoc: retryWhen(Func1)Javadoc: retryWhen(Func1,Scheduler)
Sample code
1.observable.create (New observable.onsubscribe<student> () {@Override public void call (SUBSCRIBER&LT;? Super S        tudent> subscriber) {Subscriber.onnext (Getlistofstudent (). Get (0));        Subscriber.onnext (Getlistofstudent (). Get (1));        Subscriber.onnext (Getlistofstudent (). Get (2));            if (isError) {subscriber.onerror (new Throwable ("Do OnError"));        IsError = false;        } subscriber.onnext (Getlistofstudent (). Get (3));        Subscriber.onnext (Getlistofstudent (). Get (4));    Subscriber.onnext (Getlistofstudent (). Get (5)); }}). Subscribeon (Schedulers.io ()). Observeon (Androidschedulers.mainthread ()). Subscribe (New Subscriber<stu                Dent> () {@Override public void OnStart () {Super.onstart ();            Madastudent.clear ();            } @Override public void oncompleted () {log.i (TAG, "do oncompleted");   } @Override         public void OnError (Throwable e) {log.i (TAG, "do OnError");                } @Override public void OnNext (Student Student) {log.i (TAG, "do OnNext");                LOG.I (TAG, student.tostring ());            Madastudent.adddata (student);    }); 2.***.retrywhen (new Func1<observable<? extends Throwable>, observable<?>> () {@Override Public observable<throwable> call (observable<? extends throwable> Observable) {return observable.err    or (New Throwable ("Do Retrywhen")); }})****
Log Print

1.
Operateactivity:do OnNext
Student{id= ' 1 ' name= ' A ', age=23}
Operateactivity:do OnNext
Student{id= ' 2 ' name= ' B ', age=33}
Operateactivity:do OnNext
Student{id= ' 3 ' name= ' C ', age=24}
Operateactivity:do OnNext
Student{id= ' 1 ' name= ' A ', age=23}
Operateactivity:do OnNext
Student{id= ' 2 ' name= ' B ', age=33}
Operateactivity:do OnNext
Student{id= ' 3 ' name= ' C ', age=24}
Operateactivity:do OnNext
Student{id= ' 4 ' name= ' D ', age=24}
Operateactivity:do OnNext
Student{id= ' 5 ' name= ' E ', age=33}
Operateactivity:do OnNext
Student{id= ' 6 ' name= ' F ', age=23}
2.
Do OnError

Example parsing

In Example 1, in the parameter function of Retrywhend (FUNC1), a observable object that can emit data is created and returned, whereas in Example 2, its parameter function creates and returns a observable of the emitted onerror notification. With log printing, example 1 intercepts the ONERROR notification in the original observable and re-subscribes to the original observable, but in Example 2, the observer receives the ONERROR notification, means that the onerror notice in the original observable was not intercepted and fired directly. In Example 2, the differences between Retrywhen () and retry () are reflected.

Error handling of Rxjava

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.