Skip to content

Commit

Permalink
refactor(aio): switch to pipeable RxJS operators (angular#22872)
Browse files Browse the repository at this point in the history
PR Close angular#22872
  • Loading branch information
gkalpak authored and leo6104 committed Mar 25, 2018
1 parent a69991d commit 0f29432
Show file tree
Hide file tree
Showing 24 changed files with 196 additions and 192 deletions.
2 changes: 1 addition & 1 deletion aio/scripts/_payload-limits.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"master": {
"uncompressed": {
"inline": 1971,
"main": 595662,
"main": 584136,
"polyfills": 40272,
"prettify": 14888
}
Expand Down
4 changes: 2 additions & 2 deletions aio/src/app/app.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { MatProgressBar, MatSidenav } from '@angular/material';
import { By } from '@angular/platform-browser';

import { Observable, timer } from 'rxjs';
import 'rxjs/add/operator/mapTo';
import { mapTo } from 'rxjs/operators';

import { AppComponent } from './app.component';
import { AppModule } from './app.module';
Expand Down Expand Up @@ -1371,6 +1371,6 @@ class TestHttpClient {
}

// Preserve async nature of `HttpClient`.
return timer(1).mapTo(data);
return timer(1).pipe(mapTo(data));
}
}
8 changes: 4 additions & 4 deletions aio/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { SearchService } from 'app/search/search.service';
import { TocService } from 'app/shared/toc.service';

import { BehaviorSubject, combineLatest, Observable } from 'rxjs';
import 'rxjs/add/operator/first';
import { first, map } from 'rxjs/operators';

const sideNavView = 'SideNav';

Expand Down Expand Up @@ -143,7 +143,7 @@ export class AppComponent implements OnInit {
// Compute the version picker list from the current version and the versions in the navigation map
combineLatest(
this.navigationService.versionInfo,
this.navigationService.navigationViews.map(views => views['docVersions']))
this.navigationService.navigationViews.pipe(map(views => views['docVersions'])))
.subscribe(([versionInfo, versions]) => {
// TODO(pbd): consider whether we can lookup the stable and next versions from the internet
const computedVersions: NavigationNode[] = [
Expand Down Expand Up @@ -171,7 +171,7 @@ export class AppComponent implements OnInit {

this.navigationService.versionInfo.subscribe(vi => this.versionInfo = vi);

const hasNonEmptyToc = this.tocService.tocList.map(tocList => tocList.length > 0);
const hasNonEmptyToc = this.tocService.tocList.pipe(map(tocList => tocList.length > 0));
combineLatest(hasNonEmptyToc, this.showFloatingToc)
.subscribe(([hasToc, showFloatingToc]) => this.hasFloatingToc = hasToc && showFloatingToc);

Expand All @@ -183,7 +183,7 @@ export class AppComponent implements OnInit {
combineLatest(
this.documentService.currentDocument, // ...needed to determine host classes
this.navigationService.currentNodes) // ...needed to determine `sidenav` state
.first()
.pipe(first())
.subscribe(() => this.updateShell());
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError, map } from 'rxjs/operators';
import { Logger } from 'app/shared/logger.service';
import { CONTENT_URL_PREFIX } from 'app/documents/document.service';
const announcementsPath = CONTENT_URL_PREFIX + 'announcements.json';
Expand Down Expand Up @@ -58,15 +59,17 @@ export class AnnouncementBarComponent implements OnInit {

ngOnInit() {
this.http.get<Announcement[]>(announcementsPath)
.catch(error => {
this.logger.error(new Error(`${announcementsPath} request failed: ${error.message}`));
return [];
})
.map(announcements => this.findCurrentAnnouncement(announcements))
.catch(error => {
this.logger.error(new Error(`${announcementsPath} contains invalid data: ${error.message}`));
return [];
})
.pipe(
catchError(error => {
this.logger.error(new Error(`${announcementsPath} request failed: ${error.message}`));
return [];
}),
map(announcements => this.findCurrentAnnouncement(announcements)),
catchError(error => {
this.logger.error(new Error(`${announcementsPath} contains invalid data: ${error.message}`));
return [];
}),
)
.subscribe(announcement => this.announcement = announcement);
}

Expand Down
12 changes: 6 additions & 6 deletions aio/src/app/custom-elements/api/api.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import { Injectable, OnDestroy } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

import { ReplaySubject, Subject } from 'rxjs';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/takeUntil';
import { takeUntil, tap } from 'rxjs/operators';

import { Logger } from 'app/shared/logger.service';
import { DOC_CONTENT_URL_PREFIX } from 'app/documents/document.service';
Expand Down Expand Up @@ -34,7 +32,7 @@ export class ApiService implements OnDestroy {
private firstTime = true;
private onDestroy = new Subject();
private sectionsSubject = new ReplaySubject<ApiSection[]>(1);
private _sections = this.sectionsSubject.takeUntil(this.onDestroy);
private _sections = this.sectionsSubject.pipe(takeUntil(this.onDestroy));

/**
* Return a cached observable of API sections from a JSON file.
Expand Down Expand Up @@ -70,8 +68,10 @@ export class ApiService implements OnDestroy {
// TODO: get URL by configuration?
const url = this.apiBase + (src || this.apiListJsonDefault);
this.http.get<ApiSection[]>(url)
.takeUntil(this.onDestroy)
.do(() => this.logger.log(`Got API sections from ${url}`))
.pipe(
takeUntil(this.onDestroy),
tap(() => this.logger.log(`Got API sections from ${url}`)),
)
.subscribe(
sections => this.sectionsSubject.next(sections),
(err: HttpErrorResponse) => {
Expand Down
5 changes: 2 additions & 3 deletions aio/src/app/custom-elements/code/code.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MatSnackBar } from '@angular/material';
import { By } from '@angular/platform-browser';
import { NoopAnimationsModule } from '@angular/platform-browser/animations';
import 'rxjs/add/operator/first';
import 'rxjs/add/operator/toPromise';
import { first } from 'rxjs/operators';

import { CodeComponent } from './code.component';
import { CodeModule } from './code.module';
Expand Down Expand Up @@ -65,7 +64,7 @@ describe('CodeComponent', () => {
describe('pretty printing', () => {
const untilCodeFormatted = () => {
const emitter = hostComponent.codeComponent.codeFormatted;
return emitter.first().toPromise();
return emitter.pipe(first()).toPromise();
};
const hasLineNumbers = async () => {
// presence of `<li>`s are a tell-tale for line numbers
Expand Down
4 changes: 2 additions & 2 deletions aio/src/app/custom-elements/code/code.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { Logger } from 'app/shared/logger.service';
import { PrettyPrinter } from './pretty-printer.service';
import { CopierService } from 'app/shared/copier.service';
import { MatSnackBar } from '@angular/material/snack-bar';
import 'rxjs/add/operator/do';
import { tap } from 'rxjs/operators';

/**
* If linenums is not set, this is the default maximum number of lines that
Expand Down Expand Up @@ -120,7 +120,7 @@ export class CodeComponent implements OnChanges {

this.pretty
.formatCode(leftAlignedCode, this.language, this.getLinenums(leftAlignedCode))
.do(() => this.codeFormatted.emit())
.pipe(tap(() => this.codeFormatted.emit()))
.subscribe(c => this.setCodeHtml(c), err => { /* ignore failure to format */ }
);
}
Expand Down
27 changes: 14 additions & 13 deletions aio/src/app/custom-elements/code/pretty-printer.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { Injectable } from '@angular/core';

import { from as fromPromise, Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/first';
import { first, map, share } from 'rxjs/operators';

import { Logger } from 'app/shared/logger.service';

Expand All @@ -21,7 +20,7 @@ export class PrettyPrinter {
private prettyPrintOne: Observable<PrettyPrintOne>;

constructor(private logger: Logger) {
this.prettyPrintOne = fromPromise(this.getPrettyPrintOne()).share();
this.prettyPrintOne = fromPromise(this.getPrettyPrintOne()).pipe(share());
}

private getPrettyPrintOne(): Promise<PrettyPrintOne> {
Expand Down Expand Up @@ -50,15 +49,17 @@ export class PrettyPrinter {
* @returns Observable<string> - Observable of formatted code
*/
formatCode(code: string, language?: string, linenums?: number | boolean) {
return this.prettyPrintOne.map(ppo => {
try {
return ppo(code, language, linenums);
} catch (err) {
const msg = `Could not format code that begins '${code.substr(0, 50)}...'.`;
console.error(msg, err);
throw new Error(msg);
}
})
.first(); // complete immediately
return this.prettyPrintOne.pipe(
map(ppo => {
try {
return ppo(code, language, linenums);
} catch (err) {
const msg = `Could not format code that begins '${code.substr(0, 50)}...'.`;
console.error(msg, err);
throw new Error(msg);
}
}),
first(), // complete immediately
);
}
}
21 changes: 11 additions & 10 deletions aio/src/app/custom-elements/contributor/contributor.service.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/publishLast';
import { ConnectableObservable, Observable } from 'rxjs';
import { map, publishLast } from 'rxjs/operators';

import { Contributor, ContributorGroup } from './contributors.model';

Expand All @@ -22,9 +21,9 @@ export class ContributorService {
}

private getContributors() {
const contributors = this.http.get<{[key: string]: Contributor}>(contributorsPath)
const contributors = this.http.get<{[key: string]: Contributor}>(contributorsPath).pipe(
// Create group map
.map(contribs => {
map(contribs => {
const contribMap: { [name: string]: Contributor[]} = {};
Object.keys(contribs).forEach(key => {
const contributor = contribs[key];
Expand All @@ -38,10 +37,10 @@ export class ContributorService {
});

return contribMap;
})
}),

// Flatten group map into sorted group array of sorted contributors
.map(cmap => {
map(cmap => {
return Object.keys(cmap).map(key => {
const order = knownGroups.indexOf(key);
return {
Expand All @@ -51,10 +50,12 @@ export class ContributorService {
} as ContributorGroup;
})
.sort(compareGroups);
})
.publishLast();
}),

contributors.connect();
publishLast(),
);

(contributors as ConnectableObservable<ContributorGroup[]>).connect();
return contributors;
}
}
Expand Down
14 changes: 7 additions & 7 deletions aio/src/app/custom-elements/resource/resource.service.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/publishLast';
import { ConnectableObservable, Observable } from 'rxjs';
import { map, publishLast } from 'rxjs/operators';

import { Category, Resource, SubCategory } from './resource.model';
import { CONTENT_URL_PREFIX } from 'app/documents/document.service';
Expand All @@ -20,11 +19,12 @@ export class ResourceService {

private getCategories(): Observable<Category[]> {

const categories = this.http.get<any>(resourcesPath)
.map(data => mkCategories(data))
.publishLast();
const categories = this.http.get<any>(resourcesPath).pipe(
map(data => mkCategories(data)),
publishLast(),
);

categories.connect();
(categories as ConnectableObservable<Category[]>).connect();
return categories;
};
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { LocationService } from 'app/shared/location.service';
import { SearchResults } from 'app/search/interfaces';
import { SearchService } from 'app/search/search.service';
Expand All @@ -15,9 +16,9 @@ export class FileNotFoundSearchComponent implements OnInit {
constructor(private location: LocationService, private search: SearchService) {}

ngOnInit() {
this.searchResults = this.location.currentPath.switchMap(path => {
this.searchResults = this.location.currentPath.pipe(switchMap(path => {
const query = path.split(/\W+/).join(' ');
return this.search.search(query);
});
}));
}
}
27 changes: 14 additions & 13 deletions aio/src/app/documents/document.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';

import { AsyncSubject, Observable, of } from 'rxjs';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/switchMap';
import { catchError, switchMap, tap } from 'rxjs/operators';

import { DocumentContents } from './document-contents';
export { DocumentContents } from './document-contents';
Expand Down Expand Up @@ -41,7 +40,7 @@ export class DocumentService {
private http: HttpClient,
location: LocationService) {
// Whenever the URL changes we try to get the appropriate doc
this.currentDocument = location.currentPath.switchMap(path => this.getDocument(path));
this.currentDocument = location.currentPath.pipe(switchMap(path => this.getDocument(path)));
}

private getDocument(url: string) {
Expand All @@ -60,15 +59,17 @@ export class DocumentService {
this.logger.log('fetching document from', requestPath);
this.http
.get<DocumentContents>(requestPath, {responseType: 'json'})
.do(data => {
if (!data || typeof data !== 'object') {
this.logger.log('received invalid data:', data);
throw Error('Invalid data');
}
})
.catch((error: HttpErrorResponse) => {
return error.status === 404 ? this.getFileNotFoundDoc(id) : this.getErrorDoc(id, error);
})
.pipe(
tap(data => {
if (!data || typeof data !== 'object') {
this.logger.log('received invalid data:', data);
throw Error('Invalid data');
}
}),
catchError((error: HttpErrorResponse) => {
return error.status === 404 ? this.getFileNotFoundDoc(id) : this.getErrorDoc(id, error);
}),
)
.subscribe(subject);

return subject.asObservable();
Expand All @@ -90,7 +91,7 @@ export class DocumentService {
private getErrorDoc(id: string, error: HttpErrorResponse): Observable<DocumentContents> {
this.logger.error(new Error(`Error fetching document '${id}': (${error.message})`));
this.cache.delete(id);
return Observable.of({
return of({
id: FETCHING_ERROR_ID,
contents: FETCHING_ERROR_CONTENTS
});
Expand Down

0 comments on commit 0f29432

Please sign in to comment.