Skip to content

Commit

Permalink
adriancarriger#35 WIP: try to use child_added event to avoid updating…
Browse files Browse the repository at this point in the history
… whole array for single item being added
  • Loading branch information
ciekawy committed May 17, 2017
1 parent e772ad9 commit 8087d21
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
29 changes: 28 additions & 1 deletion src/database/database.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,12 @@ export const Ref = {
ref: {key: 'key-1'},
push: undefined,
resolve: undefined,
handlers: {
// dumb handler to avoid checks
'child_added': () => {}
},
on(event, callback) { this.handlers[event] = callback; },
off(event) { this.handlers[event] = () => {}; },
toString: () => 'https://angularfire2-offline.firebaseio.com/key-1',
database: {
ref: () => {
Expand All @@ -545,16 +551,37 @@ export const Ref = {
};

@Injectable()
export class MockFirebaseListObservable<T> extends Subject<T> {
export class MockFirebaseListObservable<T> extends Subject<Array<T>> {
history = [];
$ref = Ref.$ref;
oldValue: Array<T> = [];

constructor() {
super();
}
remove() {
this.history.push('remove');
return new Promise(resolve => resolve());
}

next(value: Array<T>) {
let i = 0, j = 0;

while (i < this.oldValue.length && j < value.length) {
if ((<any>value[i]).key < (<any>this.oldValue[j]).key) {
this.child_added(value[i], j === 0 ? null : (<any>this.oldValue[j - 1]).key);
} else if ((<any>value[i]).key > (<any>this.oldValue[j]).key) {
j++; // TODO call child_removed
} else if ((<any>value[i]).val() !== (<any>this.oldValue[j]).val()) {
i++; j++; // TODO call child_changed
}
}

this.oldValue = value;
super.next(value);
}
child_added = (value, previousChild) =>
this.$ref.handlers['child_added'](value, previousChild);
}

@Injectable()
Expand Down
18 changes: 16 additions & 2 deletions src/database/database.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,11 +307,25 @@ export class AngularFireOfflineDatabase {
} else {
this.listCache[key].sub.uniqueNext( cacheValue );
}
this.setList(key, value);
});

ref.$ref.on('child_added', (childSnapshot: any, prevChildName: any) => {
let parentKey = childSnapshot.ref.parent.key;
this.localForage.setItem(`read/object${parentKey}/${childSnapshot.key}`, childSnapshot.val());
this.localForage.getItem(`read/list${parentKey}`)
.then(keys => keys.reduce(
(arr, _key) => {
_key === prevChildName ? arr.push(_key, childSnapshot.key) : arr.push(_key);
return arr;
}), [])
.then(keys => this.localForage.setItem(`read/list${parentKey}`, keys));
});

this.listCache[key].sub.subscribe({
complete: () => subscription.unsubscribe()
complete: () => {
subscription.unsubscribe();
ref.$ref.off('child_added');
}
});

// Local
Expand Down

0 comments on commit 8087d21

Please sign in to comment.