Skip to content
This repository has been archived by the owner on Sep 4, 2020. It is now read-only.

#35 WIP: try to use child_added event to avoid updating whole array for single item being added #37

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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