Rxjava Starter Series three, responsive programming

Source: Internet
Author: User
Tags call back

Rxjava Starter Series three, responsive programming

In Rxjava Introductory series one, I introduce you to Rxjava's infrastructure. Rxjava Introductory Series Two, I show you the various awesome operators that Rxjava offers. But you may still not be able to persuade yourself to use Rxjava, In this blog post I will show you the other advantages that Rxjava offers, and if you know these advantages, you really want to use Rxjava.

Exception handling

So far, I have not introduced the OnComplete () and OnError () methods. These two methods are used to stop the observable from continuing to issue events and to tell the Observer why it stopped (stopped normally or because an error occurred).

The Subscriber object has the ability to listen to the OnComplete () and OnError () methods, allowing us to use the two functions in part of the code:

Observable.just ("Hello, world!."). Map (S-potentialexception). Map (S-anotherpotentialexception (s)). Subscribe (NewSubscriber<string> () {@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!"); }    })

It is possible for the potentialexception () and Anotherpotentialexception () methods in the code to throw an error exception at run time, and each observable will call back oncompleted () when stopped or the OnError () method. Therefore, the program either outputs "completed" (normal stop) or outputs "Ouch" (because of an exception thrown).

This exception handling pattern has several advantages:

    1. Whenever an exception occurs, the OnError () method is recalled.
      This makes exception handling very simple, and I just need to do the exception handling in the OnError () method.
    2. Operator does not need to handle exceptions.
      The exception is given to subscriber, so that if an exception is made to the observable chain call, the Subscriber OnError () method is executed directly.
    3. You can know when Subscriber has received the complete information.
      Knowing when an event is going to end can be a great help to your code's process calls.

I found Rxjava this exception-handling mode is simpler than the traditional exception-handling pattern. In traditional exception handling mode, you handle error exceptions by setting a callback function. This not only leads to a lot of repetitive code, but it also means that each callback function needs to know what kind of error exception it needs to handle. means that the exception callback handler function and the caller are tightly coupled.

With Rxjava, your observable object does not need to know how to handle errors and exceptions, and the operators in your chained calls do not need to know how to handle the exception, and once a run-time error occurs, the operator is skipped and the error is given to Subscriber to handle.

Scheduler

The Android app you write will definitely have the code to send the network request. Sending a network request is a very time-consuming operation, so you want to establish a connection pull data in a child thread. This time, the problem comes.

Writing an Android multithreaded program is difficult because you have to know which part of the code should run on which thread, or your app will probably crash. A typical crash scenario is when you try to modify the view from a non-main thread, the Android system will error.

In Rxjava, you can use the Subscribeon () method to tell observable which thread the object code is running on, and you can use the Observeon () method to tell the Subscriber which thread the object code is running on:

myObservableServices.retrieveImage(url)    .subscribeOn(Schedulers.io())    .observeOn(AndroidSchedulers.mainThread())    .subscribe(bitmap -> myImageView.setImageBitmap(bitmap));

Isn't it simple? The code before subscriber is running in the IO thread, and the Subscriber code runs in the main thread, so the last Myimageview is able to update its UI in the main thread.

The worst part is I can add Subscribeon () and Observeon () to any observable object! They are also operators! I don't need to care about observable and its previous operators, just by using these two operators I can easily implement thread scheduling.

Using Asynctask or a similar asynchronous framework, I had to design my code to find out which part of the code needed to be executed concurrently. But with Rxjava, my code stays the same, and I just need to add those two operators where the thread is scheduled.

Subscription

I have concealed one thing from you in my previous blog. When you call the Observable.subscribe () method, the subscription object is returned. It represents the subscription relationship between observable and subscriber.

Subscription subscription = Observable.just("Hello, World!")    .subscribe(s -> System.out.println(s));

You can use the subscription object to cancel the Subscriber subscription relationship to observable:

subscription.unsubscribe();System.out.println("Unsubscribed=" + subscription.isUnsubscribed());// Outputs "Unsubscribed=true"

This is another great feature of Rxjava, and when you use subscription to unsubscribe, you stop the entire observable chain call. If you have a series of very complex chained operator calls, Using the Unsubscribe method immediately stops the chained calling code being executed, and you do not need to do any additional work.

Summarize

Remember this is just Rxjava's introductory series. Rxjava has so many features and implementation details that you need to learn (such as back pressure). I'm not using Rxjava to implement all of the code, I'm just a little bit complicated enough to have to simplify it to a certain extent before using Rxjava.

Originally I planned this article as the end of the Rxjava Primer series, but I received a lot of messages hoping I could introduce rxjava how to use it specifically in Android. So, I went on to write the Rxjava introductory article four. I hope that this tutorial series will impress you with the interesting framework of getting started with Rxjava.

Original link

Grokking RxJava, part 3:reactive with benefits

Rxjava Starter Series three, responsive programming

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.