I agree that web development is changing and I need to deal with RxJS. I am currently developing a web application using Angular 2.0.0-beta.15.
I follow the excellent ng-book 2 (is such advertising allowed?) It covers the broad, shallow touches of some important concepts in RxJS and provides links for further reading. I read and understood the source code and the accompanying explanation, but I blushed a little about some details regarding Subject in particular and how Angular 2 components consume these Subject streams.
I added the code from the book:
export class SubmitResourceComponent { private _newResourceTags: Subject<Tag> = new Subject<Tag>(); private _resourceTags: Observable<Tag[]>; private _tagUpdates: Subject<any> = new Subject<any>(); private _create: Subject<Tag> = new Subject<Tag>(); private _remove: Subject<Tag> = new Subject<Tag>(); constructor() { this._resourceTags = this._tagUpdates .scan((tags: Tag[], operation: ITagsOperation) => operation(tags), initialTags); this._create .map((tag: Tag): ITagsOperation => (tags: Tag[]) => _.uniq(tags.concat(tag))) .subscribe(this._tagUpdates); this._remove .map((tag: Tag): ITagsOperation => (tags: Tag[]) => _.without(tags, tag)) .subscribe(this._tagUpdates); this._newResourceTags.subscribe(this._create); } get resourceTags(): Observable<Tag[]> { return this._resourceTags; } protected addTagToResource(tag: Tag): void { this._create.next(tag); } protected removeTagFromResource(tag: Tag): void { this._remove.next(tag); } }
And I consume _resourceTags as follows:
<button class="btn" *ngFor="#tag of resourceTags | async" (click)="removeTagFromResource(tag)">{{ tag.name }}</button>
What I cannot understand, even with excellent support on gitter forums, is why the user interface displays all the tags that fit in _resourceTags Subject . I would suggest that the stream looks like a rubber tube: as soon as an element has been pressed into a Subject and published to any Observer (in this case, a UI element), does it not evaporate and disappear? Does it stay in the stream / pipe / Subject ? How does a user interface element subscribe to a Subject ? Am I thinking about it wrong? Do I need a complete psychiatric restructuring / transplant?
So many questions!
source share