Skip to content

Commit c74e1b4

Browse files
committed
fix(async-children): create observable for aysnc children only once (fixes #80)
1 parent a0b6f0a commit c74e1b4

3 files changed

Lines changed: 13 additions & 7386 deletions

File tree

src/tree.ts

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -82,20 +82,25 @@ export class Tree {
8282
* @returns {Observable<Tree[]>} An observable which emits children once they are loaded.
8383
*/
8484
public get childrenAsync(): Observable<Tree[]> {
85-
if(this.canLoadChildren()) {
86-
setTimeout(() => this._childrenLoadingState = ChildrenLoadingState.Loading);
87-
return new Observable((observer: Observer<Tree[]>) => {
85+
if (this.canLoadChildren()) {
86+
return this.childrenAsyncOnce();
87+
}
88+
return Observable.of(this.children);
89+
}
90+
91+
private childrenAsyncOnce: () => Observable<Tree[]> = _.once(() => {
92+
return new Observable((observer: Observer<Tree[]>) => {
93+
setTimeout(() => {
94+
this._childrenLoadingState = ChildrenLoadingState.Loading;
8895
this._loadChildren((children: TreeModel[]) => {
8996
this._children = _.map(children, (child: TreeModel) => new Tree(child, this));
9097
this._childrenLoadingState = ChildrenLoadingState.Completed;
9198
observer.next(this.children);
9299
observer.complete();
93100
});
94101
});
95-
}
96-
97-
return Observable.of(this.children);
98-
}
102+
});
103+
});
99104

100105
/**
101106
* Create a new node in the current tree.

test/tree.spec.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -744,6 +744,7 @@ describe('Tree', () => {
744744
});
745745

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

0 commit comments

Comments
 (0)