In-depth introduction to RxJava 3-benefits of response
Original article link
In the first article, I introduced the basic knowledge of RxJava. In the second article, I show you the power of operators. But you may not be convinced. In this article, I will show you some other benefits of RxJava. I believe this article is sufficient for you to use Rxjava.
Error Handling
So far, we have not introduced the onComplete () and onError () functions. These two functions are used to notify the subscriber that the observed object will stop sending data and why (successful completion or error ).
The following code shows how to use these two functions:
potentialException(s)) .map(s -> anotherPotentialException(s)) .subscribe(new Subscriber
() { @Override public void onNext(String s) { System.out.println(s); } @Override public void onCompleted() { System.out.println("Completed!"); } @Override public void onError(Throwable e) { System.out.println("Ouch!"); } });" data-snippet-id="ext.f374b507efce50bd09206da9662eabfa" data-snippet-saved="false" data-csrftoken="6c884Zbm-sPxgUkIboxH1Vpi3MqMZmBR1gMU" data-codota-status="done">
Observable.just("Hello, world!") .map(s -> potentialException(s)) .map(s -> anotherPotentialException(s)) .subscribe(new Subscriber
() { @Override public void onNext(String s) { System.out.println(s); } @Override public void onCompleted() { System.out.println("Completed!"); } @Override public void onError(Throwable e) { System.out.println("Ouch!"); } });
PotentialException () and anotherPotentialException () in the Code may throw an exception. Every Observerable object will call the onCompleted () or onError () method at the end, so "Completed!" will be printed in the Demo !" Or "Ouch !".
This mode has the following advantages:
1. An onError () will be called as long as an exception occurs.
This greatly simplifies error handling. You only need to handle errors in one place.
2. The operator does not need to handle exceptions.
Handle the exception to the subscriber. Once an exception is thrown in the call chain of the Observerable operator, the onError () method is executed directly.
3. You can know when the subscriber has received all the data.
Know when the task ends to simplify the code process. (Although it is possible that the Observable object will never end)
I think this error handling method is simpler than the traditional one. In traditional error handling, errors are usually handled in each callback. This not only leads to repeated code, but also means that every callback must know how to handle the error. Your callback code will be tightly coupled with the caller.
With RxJava, the Observable object does not need to know how to handle errors! The operator does not need to handle the error status. Once an error occurs, the current and subsequent operators are skipped. All error handling tasks are handled by the subscriber.
Scheduler
Suppose that the Android app you wrote needs to request data from the Network (I think this is necessary, is there a single machine ?). Network requests require a long call, so you plan to load data in another thread. This is the problem!
It is difficult to write a multi-threaded Android Application, because you must ensure that the code runs in the correct thread; otherwise, the app may crash. The most common is to update the UI in a non-main thread.
With RxJava, you can use subscribeOn () to specify the thread where the observer code runs, and use observerOn () to specify the thread where the subscriber runs:
myImageView.setImageBitmap(bitmap));" data-snippet-id="ext.1fda4565f75cf740bba9b0668bb2929f" data-snippet-saved="false" data-csrftoken="vcGV2WNU-Iuw9DOY5m6q8uw-kNPwFrIu7-Ws" data-codota-status="done">myObservableServices.retrieveImage(url) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(bitmap -> myImageView.setImageBitmap(bitmap));
Is it easy? Any code executed before my Subscriber is executed in the I/O thread. Finally, the view code is run in the main thread.
The best thing is that I can add subscribeOn () and observerOn () to any Observable object. These two are also operators !. I don't need to care about the Observable object and the operators on it. Only the two operators can be used to schedule tasks in different threads.
If you use AsyncTask or something similar, I will have to carefully design my code to find out what needs to be executed concurrently. With RxJava, I can keep the code unchanged and only call these two operators when concurrency is required.
Subscriptions)
When Observable. subscribe () is called, a subscribe object is returned. This object represents the relationship between the observer and the subscriber.
System.out.println(s));" data-snippet-id="ext.69a22e2d6aa4f17ec3f44e9a4b90adae" data-snippet-saved="false" data-csrftoken="zZzFuxFT-sX6XXdjRsxAYKfdQG1kwoGyp7SQ" data-codota-status="done">ubscription subscription = Observable.just("Hello, World!") .subscribe(s -> System.out.println(s));
You can use this subscriber object to operate the relationship between the observer and the subscriber.
subscription.unsubscribe();System.out.println("Unsubscribed=" + subscription.isUnsubscribed());// Outputs "Unsubscribed=true"
Another benefit of RxJava is that when it processes unsubscribing, it will stop the entire call chain. If you use a complex string of operators, calling unsubscribe will terminate at the place where it is currently executed. No extra work is required!
Summary
Remember that this series is just an introduction to RxJava. RxJava has more features I haven't introduced for you to explore (such as backpressure ). Of course, not all of my code uses a responsive approach-I only use responsive code when the code is so complex that I want to break it into simple logic.
At first, my plan was this article as a summary of this series, but I have received many requests to introduce the use of RxJava in Android, so you can continue to read the fourth article. I hope this introduction will help you start using RxJava. If you want to learn more, I suggest you read RxJava's official wiki.