angulae Observable and Rxjs

Posted by Will Poulson on Fri, 17 Sep 2021 01:07:42 +0200

Observable

Observable (observable object) is an object in the RxJS library, which can be used to handle asynchronous events, such as HTTP requests (in fact, in Angular, all HTTP requests return observable).
Perhaps you have come across something called promise before. They are essentially the same: producers actively "push" products to consumers, while consumers passively receive them, but they are still very different: Observable can send any number of values, and it will not be executed until it is subscribed! This is a feature that promise does not have.

  • Observable is used to transmit messages between sender and receiver. You can treat these messages as streams
  • When creating an Observable object, you need to pass in a function as the parameter of the constructor. This function is called the subscriber function, which is where the producer pushes messages to consumers
  • Before being subscribed by the consumer, the subscriber function will not be executed until the subscribe() function is called. The function returns a subscription object with an unsubscribe() function. The consumer can refuse to receive the message at any time!
  • The subscribe() function receives an observer object as an input parameter
  • Messages can be sent synchronously or asynchronously

observer

With an observable object (sender), you need an observer (receiver) to observe the observable object. The observer needs to implement the observer interface. It is an object that contains three attributes, all of which are functions, as follows:

Notification typeexplain
nextNecessary. Take the received value as the input parameter and execute under normal conditions. It may be performed zero or more times.
errorOptional. Execute in case of error. An error interrupts the execution of this observable object instance.
completeOptional. Execute when the transfer is complete.

subscribe

Observable starts publishing values only when someone subscribes to an instance of observable. When subscribing, first call the subscribe() method of the observable object and pass an observer object to it to receive notifications. As follows:

To demonstrate the principle of subscription, you need to create a new Observable object first. It has a constructor that can be used to create new instances, but for simplicity, you can also use some static methods defined on Observable to create some common simple Observable objects:

  • of(...items): returns an Observable instance, which sends out the values provided in the parameters one by one in a synchronous manner.
  • from(iterable): convert its parameters to an Observable instance. This method is usually used to convert an array into an Observable object (sending multiple values).
import { of } from "rxjs";
// 1. Return an observable object through the of() method and prepare to send the data of 1, 2 and 3
const observable = of(1, 2, 3);	
// 2. Implement the observer interface and the observer
const observer = {	
	next: (num: number) => console.log(num),
	error: (err: Error) => console.error('Observer got an error: ' + err),
  	complete: () => console.log('Observer got a complete notification'), 
}
// 3. Subscribe. Call the subscribe() method of the observable object to subscribe. The object passed in the subscribe() method is an observer
observable.subscribe(observer);	

After operation, the console outputs 1, 2 and 3 in turn

Subscriber function

In the above example, the of() method is used to create observable objects. This section uses constructors to create observable objects.

The Observable constructor can create any type of Observable stream. When the subscribe() method of the Observable object is executed, the constructor will run the parameters it receives as a subscription function. The subscription function receives an Observer object and publishes the value to the Observer's next() method.

// 1. Custom subscriber function
function sequenceSubscriber(observer: Observer<number>) {
  observer.next(1);
  observer.next(2);
  observer.next(3);
  observer.complete();
  return {unsubscribe() {}};
}

// 2. Create a new observable object through the constructor, and the parameter is a subscriber function
const sequence = new Observable(sequenceSubscriber);

// 3. Subscribe
sequence.subscribe({
  next(num) { console.log(num); },
  complete() { console.log('Finished sequence'); }
});

// Output:
// 1
// 2
// 3
// Finished sequence

Topics: angular