This series of articles index: "Response Spring's word Wizard".
1 The way of reactive programming 1.1 what is responsive programming?
Before you start talking about responsive programming (reactive programming), take a look at a powerful productivity tool called "responsive paradigm"-spreadsheets that we often use.
For a simple example, an e-commerce website is engaged in a promotional campaign, and any single item can participate in "199 minus 40" activities, and "over 500 packages". Foodie Xiao Ming has a choice barrier (of course, the main reason is still a word: poor), he has a habit, is to first in Excel according to the budget to calculate the things they want to buy:
I believe everyone has used the formula in Excel, which is a table that counts the amount of goods and orders payable in shopping carts, which involves some formulas:
The line in blue is a reference to the formula, it can be seen that the "amount of goods" is through the "Unit price x Quantity" obtained, "full 199 minus 40" will determine whether the product amount is 199 and reduce 40 according to the situation, the right "total order Amount" is "full 199 minus 40" The sum of the column, "Postage" will be based on the total amount of the order, "final payment" is the total amount of the order plus postage.
1.1.1 Variation Transfer (propagation of change)
Why is it that the spreadsheet software is a "responsive model", because any change in "unit price" and "quantity" will be referenced ("listen") its cells update the results in real-time, if there is a chart or PivotChart reference to the data, then the corresponding changes, so that the real-time response. The change of time even has the animation effect, the user experience first-class bar!
This is one of the core features of the response: Change delivery (propagation of changes). A cell changes, like a domino, that causes the other cells that directly and indirectly refer to it to change accordingly.
See here, you may say, "Cut ~ is not to calculate the amount of payment, the shopping site has the most basic function Ah ~", this is "responsive"? Every system that interacts with the user has to "respond" to user interaction.
But in the response programming, based on the "change transfer" characteristics, the trigger response of the subject has changed. Suppose that shopping cart management and order payments are two different modules, or at least two different classes-- Cart
and Invoice
. Perhaps our code is this:
Product.java (assuming that the product has two attributes name
and price
, for simplicity, price
no BigDecimal
type)
public class Product { private String name; private double price; // 构造方法、getters、setters }
In the cart module:
import com.example.Invoice; // 2public class Cart { ... public boolean addProduct(Product product, int quantity) { ... double figure = product.getPrice() * quantity; invoice.update(figure); // 1 ... } ...}
- Is the
Cart
method by which the object is called to Invoice
Update the order amount of the object;
Cart
Import is required in the code Invoice
.
When we look at this Excel again, we find that the "total order Amount" formula is not only in its own cell, but this formula can actively listen to and respond to the changes in the shopping cart data. For a shopping cart, it has no reference to any formula for the payment of the order. It feels like this:
Suppose the data flow has two attributes for the number of goods and changes to be manipulated product
quantity
:
public class CartEvent { private Product product; private int quantity; // 构造方法、getters、setters}
In the invoice module:
import com.example.Cart // 2public class Invoice { ... public Invoice(Cart cart) { ... this.listenOn(cart); // 1 ... } // 回调方法 public void onCartChange(CartEvent event) { ... } ...}
- It is
Invoice
the object that declares the listener on the object at the time of initialization, so that when an Cart
object responds to an Cart
event (such as adding a product), Invoice
it responds;
Invoice
Import in the code Cart
.
A friend of Java desktop Development might think of a variety of listeners in Java Swing, such as the MouseListener
ability to listen to a mouse and respond in real time. So c/S client is always more responsive than B/S web interface.
So what we're talking about here is that a producer is only responsible for generating and emitting data/events, and the consumer listens and is responsible for defining how the data/event changes are handled .
So, Cart
how do Objects "emit" data or events when they change?
1.1.2 Stream (data stream)
These data/events are sent in the form of data streams in responsive programming.
We look at the shopping cart, there are a number of goods, Xiao Ming every time to add or remove a product in the shopping cart, or adjust the purchase quantity of the goods, this event will be like an electricity through the formula string up the dominoes once. This one-time operation event is a string of data streams that, if we can respond to every event in the data stream in a timely manner, can effectively improve the response level of the system. This is another core feature of the response: data stream based.
If Xiao Ming buy goods process, in order to neither exceed budget, and can save postage, sometimes plus sometimes minus:
This one-time operation constitutes a stream of data. The code in the invoice module might be this:
public Invoice(Cart cart) { ... this.listenOn(cart.eventStream()); // 1 ... }
- Among them,
cart.eventStream()
is to listen to the operation of the shopping cart event data flow, the listenOn
method can be in the data flow of the incoming elements in turn processing.
1.1.3 Declarative (declarative)
Let's listenOn
take a look at the method:
In the invoice module, a string of formulas above is assembled into the following pseudo-code:
public void listenOn(DataStream<CartEvent> cartEventStream) { // 1 double sum = 0; double total = cartEventStream // 分别计算商品金额 .map(cartEvent -> cartEvent.getProduct().getPrice() * cartEvent.getQuantity()) // 2 // 计算满减后的商品金额 .map(v -> (v > 199) ? (v - 40) : v) // 将金额的变化累加到sum .map(v -> {sum += v; return sum;}) // 根据sum判断是否免邮,得到最终总付款金额 .map(sum -> (sum > 500) ? sum : (sum + 50)); ...
cartEventStream
is the data stream, which DataStream
is a type of data stream that can be temporarily imagined as a stream API that has been added to the data stream for the Java 8 version (the next section will say why not Java stream).
map
The method is used to map the elements in the data flow, such as the first one to cartEvent
get the price and quantity of the goods, and then figure out the amount of the operation, and the second one to see if you can enjoy the "199 minus 40" activity.
The pseudo-code here uses lambda, which is very suitable for data flow processing. It doesn't matter if you haven't touched lambda, we'll talk about it later.
This is a "declarative (declarative)" programming paradigm. With the four-string map
call, we first declare what kind of processing the data flow "will" take, and when there is data flow, it will be processed one after the other according to the well-declared process.
For example, for the first map
action:
the power of declarative programming paradigms lies in status quo. regardless of the incoming element, the computational logic is immutable, thus forming a "binding" to the computational logic.
Give a simple example to understand:
a = 1;b = a + 1;a = 2;
At this time, B is how much? In Java and most languages, the result of B is 2, and the second assignment of a does not affect the value of B.
Suppose Java introduces a new method of assignment that :=
represents a binding relationship to a, such as
a = 1;b := a + 1;a = 2;
Since B does not save a calculated value, but a binding relationship to a, so B can change according to the value of a at any time, b==3
then we can say that it :=
is a declarative assignment method. And the ordinary =
is a kind of command-type assignment method. In fact, most of our development is imperative, and if we need to use imperative programming to express similar binding relationships above, we have to b = a + 1
update B's value every time a changes and needs to get B.
So to think, "binding dollar policy" is not a declarative paradigm.
In summary, imperative is process-oriented and declarative is structure-oriented .
However, there is no difference between imperative and declarative, but the declarative approach is more suitable for flow-based processing. This is the third core feature of the response: declarative (declarative). In combination with the "Change Delivery" feature, declarative can make data-flow-based development more user-friendly.
1.1.4 Summary
In summary, responsive programming (reactive programming) is a programming paradigm based on the data stream and the declarative (declarative) of change delivery (propagation of changes).
The "change transfer" of responsive programming is equivalent to the pipeline of juice lines; In the entrance of the Orange, out of the orange juice, the watermelon, out of the watermelon juice, oranges and watermelon, as well as the fruit juice and residue in the machine, are flowing "data flow"; Piping drawings are expressed in "declarative" language.
How does this programming paradigm make Web applications more "reactive"?
We envision a scenario where we drive from the underlying database, through the persistence layer, the service layer, the model in the MVC layer, and the elements of the user's front-end interface, all using declarative programming paradigms to build a pipeline that can pass changes, so that we just update the data in the database, The user's interface on the corresponding changes, it is not beautiful? What is particularly important is that, in one place, we do not need a variety of imperative calls to pass this change, but rather the "pipelining" that is set up to deliver it automatically.
Where is this scenario used? For example, a log monitoring system, our front-end page will no longer need to through the "imperative" polling to the server constantly request data and then update, but after the establishment of a good channel, the flow of data from the system flow to the page, so as to show real-time indicator change curve, such as a social platform, friend's dynamic, Point like and message is not manual brush out, but when the background data changes automatically reflected in the interface.
How to implement this, see the next section on the introduction of responsive streaming.
(1) What is responsive programming--response spring's Word Wizard