A usage of Observable object and map in rxjs

Source code:

import { of } from 'rxjs';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';

@Injectable()
export class JerrySandBoxService{
    name = 'Jerry';
    print(){
        const observable = of(1, 2, 3);
        const opt = map(num => 'hello world: ' + num + ' done');
        const newObservable = opt(observable);
        newObservable.subscribe(data => console.log(data));
    }
}

Results of the:

The map operator receives an arrow function:


The internal realization of map: returns a new function named mapOperation that accepts a single parameter.

Now perform the opt operation:

The source is Observable, and the project is the arrow function specified by the application developer:

Constructor of Map operator:

Create a new Observable object and pass the current Observable object to the source, operator.project is the arrow function:


Call subscribe on the new Observable object:

Note this syntax: assign the operator object contained in this to the operator variable in curly braces:

The sink is the subscriber, the source is the Observable, and the operator is the arrow function:

If there is an operator, execute the arrow function first:


Pass the result returned by the arrow function as a new input parameter to the next method of the subscriber:



Finally execute the arrow function passed in when calling subscribe:

To get more original articles by Jerry, please follow the public account "Wang Zixi":

Guess you like

Origin blog.csdn.net/i042416/article/details/108599788