In layman's Rxjava three--the benefits of reactive formula

Source: Internet
Author: User
Tags throwable

Original link

In the first article, I introduced the basics of Rxjava. In the second article, I showed you the power of the operator. But you may still not be persuaded. In this article, I'm going to show you some of the other benefits of Rxjava, which I believe is enough for you to use Rxjava.

Error handling

So far, none of us have introduced the OnComplete () and onerror () functions. These two functions are used to inform subscribers that the observed object will stop sending data and why it is stopped (successful completion or error).

The following code shows how to use these two functions:

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!"); }    });

Potentialexception () and Anotherpotentialexception () in the code may throw an exception. Each Observerable object will call the oncompleted () or OnError () method at the end, so the "completed!" is printed in the demo or "ouch!".

This model has several advantages:

1. OnError () must be called whenever an exception occurs

This greatly simplifies error handling. You just need to handle the error in one place.

2. Operator does not need to handle exceptions

The exception handling is given to subscribers, and once an exception is thrown in the observerable operator invocation chain, the OnError () method is executed directly.

3. You can know when the Subscriber has received all the data.

Knowing when a task is over can help streamline the process of code. (although it is possible that the observable object will never end)

I think this kind of error handling is easier than traditional error handling. In traditional error handling, errors are usually handled in each callback. This not only leads to repetitive code, it means that each callback must know how to handle the error, and your callback code will be tightly coupled with the caller.

Using the Rxjava,observable object doesn't need to know how to handle the error at all! Operators also do not need to handle error states-If an error occurs, the current and subsequent operators are skipped. All error handling is given to subscribers.

Scheduler

Suppose you write an Android app that needs to request data from the Web (it feels like a must-have, and a single machine?). )。 Network requests take a long time, so you intend to load the data in another thread. Here's the problem!

Writing multi-threaded Android applications is difficult because you have to make sure that the code is running in the correct thread, otherwise it may cause the app to crash. The most common is to update the UI on a non-main thread.

With Rxjava, you can use Subscribeon () to specify the thread that the watcher code is running on, using Observeron () to specify the thread that the Subscriber runs:

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

Isn't it simple? Any code that executes in front of my subscriber is run in the I/O thread. Finally, the code that operates the view runs in the main thread.

Best of all, 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 what operators it has. Only these two operators can be used to schedule in different threads.

If you use Asynctask or something like that, I will have to design my code carefully to find out what parts of it need to be executed concurrently. With Rxjava, I can keep the code constant, just call the two operators when concurrency is required.

Subscribe (subscriptions)

When Observable.subscribe () is called, a subscription object is returned. This object represents the connection between the observer and the Subscriber.

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

You can use this subscription object later to manipulate the connection between the observer and the Subscriber.

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

Another benefit of Rxjava is that it stops the entire call chain when it handles unsubscribing. If you use a complex set of operators, calling unsubscribe will terminate at the point where he is currently executing. No need to do any extra work!

Summarize

Remember this series is just an introductory introduction to Rxjava. There are more features in Rxjava that I didn't introduce (such as backpressure). Of course I'm not all the code used in a responsive way – I only use responsive code when the code is so complex that I want to break it down into simple logic.

Originally, my plan was this article as a summary of this series, but I received many requests for my introduction to using Rxjava in Android, so you can continue reading the fourth article. I hope this introduction will allow you to start using Rxjava. If you want to learn more, I suggest you read the official wiki of Rxjava.

In layman's Rxjava three--the benefits of reactive formula

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.