Sam Julien, Energy Trust of Oregon
Using RxJS, developers represent asynchronous data streams with Observables, query asynchronous data streams using LINQ operators, and parameterize the concurrency in the asynchronous data streams using Schedulers.
Simply put, Rx = Observables + LINQ + Schedulers.
(Rx Docs)
The subscribe method returns a Disposable object that allows you to clean up the subscription when you're done
var source$ = Rx.Observable.range(1,4); //1,2,3,4
//map (select) & flatMap (selectMany): changes each value
//flatMap returns an observable so it works well with async operations
source$.map(x => x*2); //2, 4, 6, 8
//filter: returns only selected values based on custom logic
source$.filter(x => x % 2 === 0); //2, 4
//reduce: performs a computation on the stream and outputs the final value
source$.reduce((prev, curr) => prev + curr); //10
//scan: performs a computation on the stream but outputs intermittment values
source$.scan((prev, curr) => prev + curr); //1, 3, 6, 10
<form [ngFormModel]="form" (ngSubmit)="onSubmit()">
<p>
<label>Payee:</label>
<input type="text" ngControl="payee">
</p>
</form>
this.form.valueChanges
.map((value) => {
value.payee = value.payee.toLowerCase();
return value;
})
.filter((value) => this.form.valid)
.subscribe(validValue => ...);
<ul>
<li *ngFor="#video of videos | async">{{video | json}}</li>
</ul>
ngOnInit() {
this.getAccounts();
}
getAccounts() {
this.http.get('/accounts')
.map((res:Response) => res.json()) //map to JSON
.subscribe(
//onNext, receives HTTP response, gets data in one shot
data => { this.accounts = data},
//onError (optional), if an error code is received
err => console.error(err),
//onComplete (optional and less useful), all data returned
() => console.log('done')
);
}
getProjectsAndAccounts() {
Observable.forkJoin(
this.http.get('/projects').map((res:Response) => res.json()),
this.http.get('/accounts').map((res:Response) => res.json())
).subscribe( //We don't subscribe to the individual observables
data => { //Runs after all calls complete
this.projects = data[0]
this.accounts = data[1]
},
err => console.error(err) //Runs if either call errors
);
}
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Observable} from 'rxjs/Rx';
@Injectable()
export class ProjectService {
constructor(private http:Http) { }
getProjectsAndAccounts() {
return Observable.forkJoin(
this.http.get('/projects').map((res:Response) => res.json()),
this.http.get('/accounts').map((res:Response) => res.json())
);
}
}
import {ProjectService} from './project.service';
@Component({
//stuff and things
})
export class ProjectComponent {
constructor(private _projectService: ProjectService){}
getProjectsAndAccounts(){
this._projectService.getProjectsAndAccounts().subscribe(
data => {
this.projects = data[0];
this.accounts = data[1];
}
);
}
}
(shamelessly stolen from Rob Wormald)