官术网_书友最值得收藏!

Reactive programming

We are quite familiar with imperative programming: in our software, we ask to do something and expect a result and meanwhile, we wait, our action is blocked expecting a result. Consider this small pseudo code as an example:

var someVariable = getData()
print(someVariable)

In this couple of instructions, we will set the content of a variable from the output of a function that will return data; when the data is available, we will print it out. The really important part of this small piece of code is that our program stops until we completely get the data, this is what is called a blocking operation.

There is a way to bypass this limitation that has been used extensively in the past. For example, we could create a separate thread to get our data, but effectively, that thread will be blocked until completion, and if different requests need to handle this, we end up in the situation of creating a thread for each one, possibly using a pool, but finally we will reach a limit of how many of those threads we can handle. This is how most traditional applications work, but now, this could be improved.

Let's see some pseudo code for this in reactive programming:

subscribe(::getData).whenDone(::print)

What we are trying to do here is to subscribe to an operation and when that operation is complete, send the result to another operation. In this example, when we get the data, we will print the results; the important part of this is that after that sentence our program continues, so it could process other things; this is what is called a non-blocking operation. But this could be applied not just to a single result, we could subscribe into a reactive stream of data, and when the stream starts to flow, it will be calling our function that will be progressively printing the data that we receive.

A reactive stream is a collection of data that will continuously flow as soon as it is ready, so imagine that instead of querying a database for some results, the database starts sending results as often as it is ready. Many modern database drivers support these concepts.

This new programming model allows us to have high-performance applications to process way more requests than in a more traditional blocking model. This approach utilizes resources more effectively and this could reduce the amount of infrastructure required for our applications. But now we need to understand what are the real principles of reactive programming.

主站蜘蛛池模板: 抚顺县| 陇南市| 钟山县| 咸宁市| 潮州市| 西乌珠穆沁旗| 留坝县| 晋中市| 广昌县| 卓尼县| 嘉鱼县| 司法| 宁南县| 永嘉县| 南通市| 新竹市| 贵港市| 鹤壁市| 弥勒县| 福泉市| 宣威市| 吴川市| 石楼县| 鄢陵县| 天柱县| 井陉县| 江永县| 鹤壁市| 齐河县| 仁布县| 正蓝旗| 南召县| 青阳县| 涟源市| 沿河| 临洮县| 陈巴尔虎旗| 双峰县| 东阳市| 西盟| 图木舒克市|