- http://reactivex.io/rxjs/ has the RxJS documentation. Pick "Observable" from the menu at the left and scroll down to see all of the operators! Just have up top import 'rxjs/Rx'; at your component to let the operators be accessible.
- import { Subject } from 'rxjs/Subject';
export class PezDispenser() {
dispensePez = new Subject();
} ...is an example of using Subject out of the RxJS stuff, or perhaps more appropriately, an example of the cornerstone of the example as what is above by itself does not yet show off using it. I named this service PezDispenser as these kinda behave like Pez Dispensers, well, if Pez Dispensers had some state swappablity going on. I'll get to what I mean in a moment, but more simplistically we may get a piece of candy from our Pez Dispenser by looping it in as a service in a component and then tapping its head like so:
onTap(): void {
this.pezDispenser.dispensePez.subscribe(
(pez: Pez) => {
alert(pez.flavor);
}
);
}
I think if you call what is above first without setting what type of candy the PezDispenser will spit out that this will blow up and you'll get a nasty red message in the Google Chrome console about how flavor of undefined cannot be resolved. Then again, for all I know, this process will just hang out until the type of candy is set and the PezDispenser can actually dispense. That takes us to a second caveat. You will want to have an ngOnDestroy implementation at your component to unsubscribe for things like this to avoid memory leaks. You may set the type of Pez, perhaps from a second component, using the service as a middleman state machine for messaging between two components, like so:
setFizzy(): void {
let pez = new Pez();
pez.flavor = "Fizzy";
this.pezDispenser.dispensePez.next(pez);
}
Alright, that makes for an end to end example and yet there is nothing interesting about this without the swappable state stuff I eluded to earlier. Indeed, you don't even need a service or RxJS if you want to consistently give Pez that is Fizzy in flavor from your dispenser. The thing that makes this interesting, and you can probably see it already, is that you may set the Pez candies to be of a different variety like so:
setPeppermintSugarFree(): void {
let pez = new Pez();
pez.flavor = "Peppermint Sugar-free";
this.pezDispenser.dispensePez.next(pez);
}
For the other party (component) tapping the head, there is a what-will-I-get mystery akin to that of Erwin Schrödinger's cat in that you may either get candy that tastes like dead cat or candy that tastes like live cat and there is no way to know until you do. - .map(
(digit:number) => {
return digit + 13;
}
); ...is, of course, an example of the .map operator. Duh. - BehaviorSubject is like Subject only it starts with a default beginning placeholder setting.
Saturday, July 29, 2017
notes from some online trainings on Observables
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment