Bạn có chắc chắn muốn xóa bài viết này không ?
Everything - just like a Stream
To work with RxJS, we should think in terms of streams. The image below shows a simple stream (or pipeline) approach to handling data:
- Producer is data source that produces various forms of data to be consumed.
- Pipeline is series of logic blocks that will be executed in order when data becomes available. The data (stream of asynchronous data) are filtered and processed in different ways so that they can be more easily consumed by Consumer.
- Consumer subscribes to (or listen for) Producer's events and will do something with (consume) received data.
Any data point that holds one or more values, from a single integer to bytes of data, can be applied to the concept of a stream. Streams originate from a Producer, where data flows through a pipeline, arriving at a Consumer.
For example, we have set of operations (filter, map) that occurs between the creation of the Producer of the stream (the array) and the Consumer (the function that logs to the console):
We can create streams from static data sources: numbers (or strings), sequences, or arrays. But the power of RxJS is that it can deal with dynamic data sources in exactly the same way.
Components of an Rx Stream
A stream must always have a Producer - source of data. It is the starting point for any logic performing in RxJS.
In practice, a Producer is created from something that generates events independently (a single value, an array, mouse clicks, a bytes stream from a file). In RxJS, we call it Observable (as it's able to be observed).
Observable is responsible for something like pushing notifications, which means that it only emits events and doesn't care about consuming them.
We also need a Consumer to accept events from the Producer and process them in some specific ways. When Consumer begins listening (subscribing) to Producer for events, we now have a Stream. RxJS uses Consumer as an Observer.
With RxJS, streams travel only from the Producer to the Consumer, not the other way around. This means that streams always flow from an Observable to an Observer. In addition, both components are loosely coupled:
Once the Observer begins receiving events from the Observable, what can we do with the data?
Within the Data Pipeline.
RxJS gives us ability to manipulate and edit data when it passes from Producer to Consumer by a list of methods (Observable operators). It means that we can adapt the output of the Producer to match the expectations of the Consumer.