preface
RxJS was completely confused when I looked at the documentation, until I encountered a lot of functionality that needed to be implemented in Angular apps… RxJS perfect!
What is the observables?
An Observable is just a normal function. To make it useful, it needs to be used with an observer. The former is attacked by the latter. The observer (which we’ll cover later) is just a simple object with next, Error, and complete. Finally, you need a subscribe to start an Observable; Otherwise it won’t do anything; It can be understood that the tinder provides an environment for them to be together, and the subscription also returns an unsubscribe operation (called unsubscribe in RxJS) that can be used to cancel.
After an Observable sets up an observer, the process of connecting and retrieving raw data is called a producer, which could be a CLICK event in the DOM, an input event, or more complex HTTP communication.
To understand, let’s start with a simple example:
import { Component } from '@angular/core';
import { Observable, Subscription } from 'rxjs';
@Component({
selector: 'app-home',
template: `<input type="text"> `
})
export class HomeComponent {
ngOnInit() {
const node = document.querySelector('input[type=text]');
// The second argument input is the event name. For the input element there is an onINPUT event that accepts user input
const input$ = Observable.fromEvent(node, 'input');
input$.subscribe({
next: (event: any) = > console.log(`You just typed ${event.target.value}! `),
error: (err) = > console.log(`Oops... ${err}`),
complete: (a)= > console.log(`Complete! `)}); }}Copy the code
In the example observable.fromevent () returns an Observable, listens for input events, and sends an Event to the corresponding observer when the Event is triggered.
What is the Observer?
An observer is very simple, as in the example above subscribe is to receive an Observer method.
In Angular we subscribe would say:
input$.subscribe((event: any) = >{});Copy the code
The syntax is the same as subscribe({next, error, complete}).
Observable notifies observer Next () when it generates a new value, and calls error() when capture fails.
When an Observable is subscribed, it calls an Observer to complete() or unsubscribe(). The value is always passed to the observer.
The values produced by an Observable can be formatted or manipulated in a sequence to produce valuable data for the observer. All this is done by a sequence of chain operators, each generating a new Observable. And we also call this sequential process: flow.
What is operator?
As mentioned, an Observable can be chain-written, which means that an Observable can do something like this:
Observable.fromEvent(node, 'input')
.map((event: any) = > event.target.value)
.filter(value= > value.length >= 2)
.subscribe(value= > { console.log(value); });
Copy the code
Here is the sequence:
Suppose the user typed in: an Observable reacts to an onInput event by passing the value as a parameter to observer Next (). Map () returns a new Observable based on the contents of event.target.value and calls next() to pass it to the next observer. Filter () returns a new Observable if length >=2, and calls next() to pass it to the next observer. Finally, the result is passed to the SUBSCRIBE block. Just remember that every operator returns a new Observable, no matter how many operators there are, and only the last Observable will be subscribed to.
Don’t forget to unsubscribe.
Why do I need to unsubscribe
Observable only pushes to subscribers when data is generated, so it can push data to subscribers an infinite number of times. Because of this, it is important to unsubscribe when creating components in Angular to avoid memory leaks, knowing that wiping your ass is a must in the SPA world.
unsubscribe
As described in the previous example, a Subscription is returned after a call to subscribe(), which can be used to cancel the unsubscribe() operation. The most logical way to call it is in ngOnDestroy.
ngOnDestroy() {
this.inputSubscription.unsubscribe();
}
Copy the code
takeUnit
A very elegant way to unsubscribe
Observable.fromEvent(node, 'input')
.takeUnit((event: any) = > this.show)
.subscribe(value= > { console.log(value); });
ngOnDestory(): void {
this.show = false;
}
Copy the code
Subject
If Observable and observer are a combination of attack and receiving, Subject is both attack and receiving. Because of this, we always use new Subject when writing a Service for data passing. Here is an example:
@Injectable(a)export class MessageService {
private subject = new Subject<any> (); send(message:any) {
this.subject.next(message);
}
get(): Observable<any> {
return this.subject.asObservable(); }}Copy the code
When an F component needs to send data to an M component, we can use send() in the F component.
constructor(myService: MyService)
ngOnInit() {
this.myService.send('message');
}
Copy the code
M component receives data:
constructor(myService: MyService)
ngOnInit() {
this.myService.get.subscribe(data= > {
console.log(data); // message})}Copy the code
EventEmitter
In Angular, EventEmitter is equivalent to Subject
// my-component.component.ts
@outPut() onChange = new EventEmitter<String> (); onClick() {this.onChange.emit('hello world');
}
Copy the code
<! -- parent-coponent.component.html -->
<my-component onChange="change($event)"></my-component>
Copy the code
// parent-coponent.component.ts
change(value) {
console.log(value) // hello world
}
Copy the code
The last
RxJS has many Operators, detailed in my other article, Common Operators of RxJS(1).