头图

Observables, as the name suggests, are transactions that can be observed. In the context of Rxjs, Observables produce data over time at a certain point in time.

Observables can:

  • Constantly (forever) yields values, like the interval operator.
  • The value can be produced in one go, and then go to the complete state.
  • May generate an error and then enter the complete state.

Observable is a tool for implementing asynchronous events, such as a single action (HTTP request) or multiple repeatable actions (such as cursor movement or keypress).

Reactive programming is an approach to building applications that responds to changes that occur within the application, rather than writing the application to handle those changes. The latter is typical of Imperative Programming, or imperative programming.

To understand how Observables are designed, it is first necessary to understand several patterns of typical producer and consumer communication.

The Pull and Push models define how data producers work with data consumers.

Pull

Pull: In the case of the pull model, the consumer decides when to use or request the data. When we create a function that returns a value, that function is the producer. However, the function does not produce anything until the function is called (or asked for data).

The code that calls the function is the consumer. This call is triggered on demand by the consumer. Consumers decide communication strategies.

Push

Push: Producer-led push model. Anyone using the data has no idea when the data will arrive. They know the application logic to do when the data arrives, but the consumer doesn't decide when the data arrives.

Promises are a classic example of the push model. Promises produce data or errors when tasks complete. The callback function passed to the Promise never knows when the Promise completes, it is only responsible for what logic should be executed when the data is successfully reached or an error occurs.


注销
1k 声望1.6k 粉丝

invalid