Side effects of Rxjava

Source: Internet
Author: User
Tags emit java 8 stream

Rxjava's Observer class has many methods that can convert the emitted byte stream to any data type you need. These methods are a very central method of Rxjava and are an important reason for Rxjava to be attractive.

But some methods cannot change the flow itself anyway, I call these methods as side effects (Side Effect) methods.

On the side-effect approach, my point of view

The side effect method does not affect your byte stream itself. Conversely, when certain events occur, they are called, allowing you to handle these events.

For example: When something goes wrong, if you want to do something outside of your subscriber callback function, you can use the Doonerror () method and pass the function interface used as a parameter to the method, and any error can occur:

someObservable  .doOnError(new Action1() {     @Override     publicvoidcall(Throwable t) {        // use this callback to clean up resources,        // log the event or or report the        // problem to the user     }  })  //…

The call () method is the most important part. The code for this method will be executed before the subscriber's OnError () method is executed.

In addition to exceptions, Rxjava provides more events that can be handled:

Events and events corresponding side-effect actions
Method Functional Interface Event
Doonsubscribe () Action0 A Subscriber subscribes to the Observable
Doonunsubscribe () Action0 A Subscriber Unsubscribes from the subscription
Doonnext () Action1 The next item is emitted
Dooncompleted () Action0 The Observable would emit no more items
Doonerror () Action1 An error occurred
Doonterminate () Action0 Either an error occurred or the Observable would emit no more items
Dooneach () action1< notification< t>> Either an item is emitted, the Observable completes or an error occurred. The Notification object contains information about the type of event
Doonrequest () Action1 A downstream operator requests to emit more items

< t> either refers to the type of argument passed in, or the type that the exception can throw, such as in the case of the OnError () method

The function interfaces are all Action0 or Action1. Type. This means that a single method of these interfaces does not return any values and either has no parameters or has only one parameter, depending on the particular event.

Because these methods do not return any values, they cannot be used to change the data that is passed, so the byte stream itself cannot be changed anyway. Instead, these methods are intended to cause side-effects, such as writing something on disk, emptying the state, or anything else that can manipulate the state of the system itself rather than the event stream itself.

Note: The side-effect method itself (Doonnext (), dooncompleted (), and so on) returns an observable event, which preserves the fluency of the interface. However, the observable and source observers returned by these side-effects methods have the same type and emit the same thing.

What are they being used to do?

Since they do not change the flow itself, there must be other uses. I am here to state three examples of what you can accomplish with these methods.

Use Doonnext () to debug
Use Doonerror () as Error handling in Flatmap ().
Use Doonnext () to save/cache network Results
So let's take a concrete look at how to use these examples.

Using Doonnext () debugging
With Rxjava, sometimes you wonder why your observers don't work as expected. Especially when you're just starting to use Rxjava. Because you use a fluent API to convert some of the source code to something you want to subscribe to, you only see what you can get at the end of the transport pipeline.

When I started learning Rxjava, I had some experience with Java streaming. Likewise, you have some of the same problems here. You have a smooth and easy-to-use API to convert one type of flow to another type of stream. But why doesn't it work as expected?

In the Java 8 stream, you have the method peek () available. So when I started using Rxjava, I was curious about where I could be used more. Well, there is. In fact, Rxjava provides us with more!

You can use the Doonnext () method anywhere in the process pipeline to see what happened and get intermediate results.

Example:

Observable someobservable = Observable. from(Arrays. Aslist(New integer[]{2,3,5,7, One})). Doonnext(System. out::p rintln). Filter(Prime, Prime%2==0). Doonnext(System. out::p rintln). Count(). Doonnext(System. out::p rintln). Map(Number-String. Format("Contains%d elements", number));Subscription Subscription = O. Subscribe(System. out::p rintln, System. out::p rintln, () System. out. println("completed!"));

Here is the output of the code:

233557711114Contains4elementsCompleted!     

In this way you can collect valuable information about how the Observer object works when your observer object behaves less than you expect.

The Doonerror () and dooncompleted () methods are also useful when debugging the state of your pipeline.

Note: If you're using Rxjava to develop Android, take a look at Frodo and Fernando Ceja articles that explain the motivations for using Frodo, which allows you to debug your observers and subscribers with annotations.

Gives a way to use Doonnext () and Doonerror (), but does not change the state of too many systems-except to inflate your logs and slow down everything that runs the program.

But these operations have other uses, in fact, in these use cases, you can actually change the state of your system by using these methods, and take a look at them.

Use Doonerror () in Flatmap ()
Suppose you use retrofit to access network resources. Since retrofit has supported the observer, you can easily use these calls through Flatmap () in your processing chain.

Alas, network-related calls can cause a lot of errors-especially on mobile phones. In this case, you may not want the observer to stop working, but if you rely on the subscriber's callback method OnError () alone, it will stop working.

But keep in mind that there are observers within method Flatmap (). So you can use the Doonerror () method to change the UI in some way, but there is still a working observer flow that detects what might happen in the future.

So this case is specific as follows:

flatMap(id -> service.getPost()   .doOnError(t -> {      // report problem to UI   })   .onErrorResumeNext(Observable.empty()))

This is especially useful if you are querying your remote resources as a response to a frequently occurring UI event.

Use Doonnext () to save/cache network Results
If you create a network call at a point in the business chain, you can use Doonnext () to store the results you are getting to the local database or put the results into some caches.

It is as simple as the following lines of code:

// getOrderById is getting a fresh order// from the net and returns an observable of orders// Observable<Order> getOrderById(long id) {…}Observable.from(aListWithIds)     .-> getOrderById(id)                          .doOnNext(order-> cacheOrder(order))     // carry on with more processing  

Summarize

As you can see, there are many ways to use the Rxjava side-effects approach. Even if they don't change the flow of events themselves, they can change the state of your entire system. This can be as simple as recording the current events of the observable at a certain point in the process pipeline and writing them as the result of a network callback to the database.

Transferred from: http://codecloud.net/rxjavas-side-effect-methods-6628.html?utm_source=tuicool&utm_medium=referral
This article by the programmer of the Database technology translation team – boss 14 students translation, there is incorrect translation of the place, please help to correct, thank you for your support.
English Original: RxJava ' s Side Effect Methods
Welcome reprint, Reproduced please be sure to keep the source and source of translation, thank you for your cooperation!

Side effects 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.