@@ -42,19 +42,32 export const query = <T, Q, O>(store: Qu | |||
|
42 | 42 | }; |
|
43 | 43 | }; |
|
44 | 44 | |
|
45 | /** | |
|
46 | * Wraps the query method of the store, the resulting method takes a query | |
|
47 | * expression and returns two observable sequences. The first sequence represents | |
|
48 | * the results of the query, the second sequence provides the updates to the | |
|
49 | * query results. | |
|
50 | * | |
|
51 | * @param store The store used to query data | |
|
52 | * @param includeUpdates The flag to include item updates not only additions and | |
|
53 | * deletions. By default this flag is set to true. | |
|
54 | * @returns Two observable sequences | |
|
55 | */ | |
|
45 | 56 | export const queryEx = <T, Q, O>(store: Queryable<T, Q, O>, includeUpdates = true) => |
|
46 | 57 | (query?: Q, options?: O): [data: QueryResults<T>, updates: QueryResults<T>] => { |
|
47 | 58 | |
|
48 | const pending: T[] = []; | |
|
49 | ||
|
50 |
let results: PromiseOrValue<T[]> = |
|
|
59 | /** count active observers */ | |
|
60 | let listeners = 0; | |
|
61 | let results: PromiseOrValue<T[]> = []; | |
|
51 | 62 | |
|
52 | 63 | const data = observe<OrderedUpdate<T>>(({ next, complete, error }) => { |
|
53 | 64 | const processResults = (items: T[]) => |
|
54 | 65 | items.forEach((item, newIndex) => next({ item, newIndex, prevIndex: -1 })); |
|
55 | 66 | |
|
56 | 67 | try { |
|
57 | if (results === pending) | |
|
68 | // is there are no active observers here, we need to query actual | |
|
69 | // data from the store. | |
|
70 | if (listeners === 0) | |
|
58 | 71 | results = store.query(query, options); |
|
59 | 72 | |
|
60 | 73 | if (isPromise(results)) { |
@@ -74,8 +87,14 export const queryEx = <T, Q, O>(store: | |||
|
74 | 87 | const updates = observe<OrderedUpdate<T>>(({ next, complete, error, isClosed }) => { |
|
75 | 88 | try { |
|
76 | 89 | if (!isClosed() && isDjObservableResults<T>(results)) { |
|
90 | // subscribe fot the changes | |
|
91 | listeners++; | |
|
77 | 92 | const h = results.observe((item, prevIndex, newIndex) => next({ item, prevIndex, newIndex }), includeUpdates); |
|
78 |
return () => |
|
|
93 | return () => { | |
|
94 | // unsubscribe from changes | |
|
95 | listeners--; | |
|
96 | h.remove(); | |
|
97 | }; | |
|
79 | 98 | } else { |
|
80 | 99 | complete(); |
|
81 | 100 | } |
General Comments 0
You need to be logged in to leave comments.
Login now