In this paper, starting from vivo Internet technology WeChat public links: mp.weixin.qq.com/s/duO1pAfaK… By Yunjie Ma

ReactiveX vs. RxJava

ReactiveX stands for Reactive Extension, commonly abbreviated as Rx. Its design principle mainly uses the observer mode to distinguish the producer and consumer of data, and carries on the asynchronous processing of data through the way of event flow.

RxJava is an implementation of the ReactiveX Java language. Its programming experience is very similar to the functional programming and Stream in Java8. After mastering the relevant knowledge of Java8, you can easily get started using RxJava.

This article focuses on the understanding of several major design patterns in RxJava. By combing the relevant class diagram of Observable and explaining the relationship between these classes, people can have a clearer understanding of the working principle of event-driven in RxJava.

Concepts in RxJava

First we write a simple RxJava program that sends the elements of the array as events, which are eventually printed on the console by the consumer:

Using this simple code as a base, we’ll explain the four concepts that run through ReactiveX design: Observer, observed, event, and subscription.

  • Observer: An object that responds to an event, also known as a Consumer. In the above code, the subscirbe method takes a Consumer object, which is then wrapped as a LambdaObserver, the observer (Consumer) in this code.

  • Observable: The object that produces the event, also known as the producer, in the above code, observable.fromarray (…) Returns an Observable, which is the observed (producer) of the program.

  • Events: There are four streams of events in RxJava: onSubscribe (subscription event), onNext (normal event), onError (exception event), and onComplete (completion event). In the code above, you send the elements of the array as data in the onNext event.

  • Subscribe: Creates an observation relationship between the observer and the observed, corresponding to the subscribe() method in the code above. RxJava’s event-driven model is a “pull model” in which no event is generated until the observer subscribes to the event, and the observed produces the event only after the observer subscribes to the event.

Through time sequence analysis of the above code, we can clearly see the running process of this code. Finally, FromArrayDisposable produced onNext and onComplete events and informed Observer to consume them.

At the same time, we also see, a simple line of code, involving so many class interaction, if add some other operators, we hold to the entire program is not so easy, here we will analysis of RxJava that some main design patterns, analyzes the relationship of the class and class to more clearly understand the working principle of RxJava.

Observable

An Observable is the most important object in data processing. As can be seen from the above timing diagram, the client (message producer or consumer) only interacts with observables, and the relationship between observer and observed is realized by Observables instead of the code we display, which greatly reduces the cost of using observer mode.

So what are the main functions of An Observable? Let’s first look at the class diagram related to an Observable:

As can be seen from the picture:

  • ObservableSource An Observable implements the ObservableSource interface, which is literally an ObservableSource interface, so one of the capabilities of an Observable is that it allows observers to subscribe to events. The implementation of the event subscribe method is to call the Subscribe () method of the Observable

  • Observable is an abstract class that provides subscribeActual template method for the subclass to implement. It can be seen from the source code that the Subscribe () method of Observable will eventually delegate the subscribeActual() method of the subclass. This approach establishes a relationship between producers and consumers.

  • In addition, Observable is a factory class that provides static methods such as fromArray() and create() to create concrete observables, and flatMap() and concatMap() to wrap observables.

The existence of observables makes producers and consumers completely decoupled. Producers only need to pay attention to what kind of Observables they generate, while consumers only need to pay attention to what kind of Observables they observe.

In practical applications, Rxjava has provided a variety of operators for us to use. Producers only need to call the corresponding methods in Observable to generate the required Observable for consumers to subscribe to events. The consumer simply calls the subscribe() method of the observable to establish an observation relationship with the producer, which is extremely convenient.

Fourth, real observation

The observer mode is the core idea of RxJava design. There are always observed objects and observed objects in the observer mode. From the above analysis, it can be seen that an Observable is more of a controller than a real source of events. So what is the real producer and what is the real consumer in RxJava?

Let’s analyze three common Observables:

Observables: fromArray sends elements in an array as onNext events, Create sends custom events, and just sends single events.

As mentioned in the previous section, the actual subscription behavior is realized by subscribeActual() method in each Observable class. Let’s look at the subscribeActual() method of these three classes.

All three methods can be broken down into three steps, minus the details

  1. Create the observed object and pass it into the observer observer to establish the correlation between the two.

  2. An onSubscribe event is triggered, and the observer responds to the event.

  3. To pull events, we can look inside d.run(), source.subscribe(parent), sd.run() and see that these methods send onNext(),onError(),onComplete() and so on.

The following diagram shows the related class diagram throughout the process. The sender of the actual event is an object such as FromArrayDisposable, and the actual Observer is an entity class that implements the Observer interface. If we subscribe as a lambda expression, it is then wrapped as a default LambdaObserver object for event consumption.

Five, the need for packaging

RxJava provides rich operators, such as flatMap, concatMap, etc., which can convert events, subscribeOn, observableOn, etc., which can control production and consumption threads. These operators actually call wrapper methods in the Observable to wrap the original Observable, returning an enhanced Observable.

There are a variety of operators, but let’s take flatMap as an example to see how they work.

First, the flatMap operation returns an ObservableFlatMap object, which is created by passing in the original Observable object as an argument to the constructor.

Check out its core method subscribeActual,

You can see that the subscribeActual method for this class of objects is different from the method in the previous section. Instead of actually creating the observation relationship, it does two things:

  1. Enhance the observer by wrapping it as a MergeObserver object that responds to the generated time.

  2. Call the Subscribe method of source, which is the Observable passed in the previous constructor, to establish the observation relationship. Below is the decorator pattern RxJava relevant class diagram: all the wrapper class inherited AbstractObservableWithUpstream class, the abstract class is a type of ObservableSource member function, used to hold objects. Decorated.

An Observable supports chained operations, just like a Stream in Java 8. Consider this line of code.

When we analyze the above string of code, it will be very messy, and when we look at the source code will see the front and forget the back, but if we know enough about the RxJava packaging process, we can easily analyze the above code.

Six, the summary

RxJava packaging is strong enough, can make us very convenient to use and extend, but it also brings us to understand the working principle of the real difficulty, if we process is in a state of a little knowledge of the whole event, that we will not be able to calmly to asynchronous orchestration of services, in the actual development process can also be difficult to find the root cause of the problem.

This paper mainly analyzes the main design patterns in RxJava, including template mode, factory mode, observer mode, decorator mode, understand these design patterns, understand the relationship between classes in RxJava, we can know the process of the whole event, analysis code can also get twice the result with half the effort.

For more content, please pay attention to vivo Internet technology wechat public account

Note: To reprint the article, please contact our wechat account: Labs2020.