preface

The article almost changed from why I should use RXJS to why I should use RXJS, a short sentence reflects the extensive and profound Chinese. I first learned about RXJS when I learned about angular updates in ’18 (Angular forever! . At that time, I also bought cheng Mo Da Shen’s book (RXJS in a simple way) and read it carefully. It still lies next to me, in case I don’t know how to write this article, I can copy some.

start

RXJS is mainly a set of functional and responsive programming features, and good at handling asynchronous solutions (copied from the Book of Cheng Mo Da Shen). In RXJS, we tend to refer to its instances as data streams. To put it more figuratively, an asynchronous operation is like an untightened faucet, never knowing when the next drop of water will come out. When the data comes in, RXJS pushes it out. RXJS uses its API to help separate and simplify a lot of data processing, including consolidation, filtering, and transformation, as it comes in.

Introduction to the

RXJS can handle synchronous data, but the combination of the Map and filter apis now does the trick, making it less of a necessity. To get a feel for RXJS, write a simple example.

Interval is a create operator that pushes one piece of data downstream every 1000ms (0,1,2), and take is a filter operator that takes only the first three pieces of data pushed upstream. Subcrible means to subscribe to the data stream and takes three parameters, next, error, and the corresponding handler when complete is triggered. This is a simple combination of operators, and here is my blind beep moment. In addition, many of the following examples use the interval operator instead of the real data stream to simplify the code, whereas in practice we mostly use the Subject instance to push the data.

I thought RXJS was a good use

There are a lot of features that you can do with RXJS that look cool, but you probably don’t need to use them in real development. Deliberately using them in a project can be counterproductive. Here are a few examples.

1. Racing problem

When we use part of mobile phone numbers for fuzzy search, because the customer input too fast, resulting in a very short interval between requests, the server returned data before and after a slight deviation, will lead to the content presented is inconsistent with the expected.

In the example above, where request is used to simulate HTTP requests and interval is used to simulate data streams, you can see that the final print is 1(interval increments from 0), indicating that the first request was ignored. Since switchMap unsubscribes to the previous data when it generates new data upstream, that is, by the time we receive a 1, the 0 500ms ago has already been unsubscribed, and its request will not affect our results. However, in order to ensure server performance, people will use throttling to avoid the problem of racing, this seemingly convenient thing. To be honest, it’s kind of lame.

2. Throttling and shaking prevention

And that was it. Rxjs also provides throttled and shudderproof solutions. For a small example of shudderproof, use fromEvent to listen for input events in the input box. Then use debounceTime to perform a shudderproof operation and print out the values after the input has stopped changing for 500ms.

At first glance, it looks simple and elegant without the console for debugging, but I can’t help but want to give it a try. In React, Vue, or Angular, we use the framework’s syntactically bound input. We don’t use fromEvent instead. Also, it’s not too much trouble to write your own anti – shake.

It not only achieves the same function, but also has no problems in the combination of the framework.

3. Status management

Indeed, we can implement state management using the Subject instance in RXJS. But for me, I’m used to redux and VUex, so why would I have to make a whole set of RXJS on my own to implement state management, and I have to convince other team members to do it together, which at least seems like a thankless task? It can be used for demo writing, but it will not be used in production.

RXJS really works

Although there are a few small examples above, writing is about suppressing first and then raising. So, I have to say, RXJS in some ways, it really makes me feel simple and convenient!

1.Websocket

In this example, there are two buttons on the page. Click button 1 to open webSocket and click button 2 to close webSocket

At the code level, it is very convenient to implement WebSocket using RX. Moreover, when you have multiple code subscribed to webSocket stream, RXJS will disconnect after all of your code has unsubscribed. Or you can call unSubscribe.complete() to end the data flow directly.

2. Filter and process asynchronous data

This is where I really feel I need RXJS, and where it’s really strong.

1. I want to be a demand, for example, in obtain five effective data (for example, more than 3) later, stop to read data, in practice, we need to judge whether the data is valid, and then for a count operation, and after five hits and a cancelled, so in RXJS is much simpler.

2. For example, I want to filter out of every 1 second, passed the data flow, don’t repeat data, in the original operation, we need to set a timer, and set up a store data array, and then judge the new data and if there is any duplicate values in the array data, and using RXJS, also will be much simpler.

The interval of 1000ms should output 10 values, but because of the duplicate values, only 1,2,3,4 values appear in every 1000ms, completing the filtering of duplicate data.

There are many other apis like this, and using a combination of them for asynchronous data processing can really make our business code more elegant and readable.

3. Publish subscriptions

In actual business, I need to manage the state of many table components. However, if I put the state in OBJ of VUEX and use the id corresponding to the state to reference state in each table component, once the state of any table changes, obJ will change and all table components will be updated. On Android Pad, Rendering performance was severely affected, so we switched to a publish-subscribe model, controlling the state of each table separately to reduce component updates and improve performance. The code is simplified to something like this, leaving out the source of the data stream (websocket) and the logic to remove it when the component is uninstalled.

Equivalent to writing an intermediate layer, to maintain and push information table status. But as you iterate and integrate with the business, the code in this middle tier becomes less and less pure and difficult to maintain (mostly because you didn’t write it well enough). Therefore, I thought that I could use RXJS to sort out this logic.

The data is fetched from webSocket, filtered and processed, and passed to Subject, and the component simply subscribes to Output $to get the passed value, bypassing the code needed to build the middle tier. But there are also disadvantages, the original release subscription model, can according to id need to run the specified callback function, but after using the Subject, push all the components are received data, need to make a layer at the component level data filtering, but because you just need to judge whether the current table data effectively, will have little impact on performance. At the code level, it’s much cleaner and easier to read than before, and the business logic can go back to components instead of being written in the middle tier.

conclusion

Although RX has been studied for a long time, and books and documents have been reviewed for several times, it is still seldom used in the actual project. I hope you can correct the wrong writing or insufficient understanding. Including before writing the article also saw the RXJS article written by cheng Qingsong big man in the group, also learned from it. It is not easy to learn a new technology or library, but when using it, we need to consider the specific use scenario and the situation of the whole team, too deliberately using the new technology stack may get half the result with twice the effort.

If this article is helpful to you, please pay attention to my public number, lazy dog small front end, thank you ~