Skip to content

Commit

Permalink
fix(async-children): create observable for aysnc children only once (f…
Browse files Browse the repository at this point in the history
…ixes #80)
  • Loading branch information
rychkog committed May 3, 2017
1 parent a0b6f0a commit c74e1b4
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 7,386 deletions.
19 changes: 12 additions & 7 deletions src/tree.ts
Expand Up @@ -82,20 +82,25 @@ export class Tree {
* @returns {Observable<Tree[]>} An observable which emits children once they are loaded.
*/
public get childrenAsync(): Observable<Tree[]> {
if(this.canLoadChildren()) {
setTimeout(() => this._childrenLoadingState = ChildrenLoadingState.Loading);
return new Observable((observer: Observer<Tree[]>) => {
if (this.canLoadChildren()) {
return this.childrenAsyncOnce();
}
return Observable.of(this.children);
}

private childrenAsyncOnce: () => Observable<Tree[]> = _.once(() => {
return new Observable((observer: Observer<Tree[]>) => {
setTimeout(() => {
this._childrenLoadingState = ChildrenLoadingState.Loading;
this._loadChildren((children: TreeModel[]) => {
this._children = _.map(children, (child: TreeModel) => new Tree(child, this));
this._childrenLoadingState = ChildrenLoadingState.Completed;
observer.next(this.children);
observer.complete();
});
});
}

return Observable.of(this.children);
}
});
});

/**
* Create a new node in the current tree.
Expand Down
1 change: 1 addition & 0 deletions test/tree.spec.ts
Expand Up @@ -744,6 +744,7 @@ describe('Tree', () => {
});

tree.switchFoldingType();
expect(tree.childrenAsync === tree.childrenAsync).toEqual(true, 'observable for children loading gets created just once');
tree.childrenAsync.subscribe(() => {
tree.childrenAsync.subscribe((children: Tree[]) => {
expect(loadCount).toEqual(1, 'children should be loaded only once');
Expand Down

0 comments on commit c74e1b4

Please sign in to comment.