@reactive-cache/core 2.9.0 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.gitattributes CHANGED
@@ -1,2 +1,2 @@
1
- # Auto detect text files and perform LF normalization
2
- * text=auto
1
+ # Auto detect text files and perform LF normalization
2
+ * text=auto
package/README.md CHANGED
@@ -12,31 +12,69 @@ $ npm install @reactive-cache/core
12
12
 
13
13
 
14
14
  ## Usage
15
-
16
15
  ```typescript
17
- import { reactiveCache } from 'reactive-cache';
16
+ import { reactiveCache } from "@reactive-cache/core";
17
+ import { first, map } from "rxjs";
18
+ import { ajax } from "rxjs/ajax";
19
+
20
+ // lets just create an observable that makes http requests
21
+ const cachedTodo = reactiveCache<Todo>(
22
+ "cachedObservable",
23
+ ajax<Todo>("https://jsonplaceholder.typicode.com/todos/1").pipe(
24
+ map((respWithMetadata) => respWithMetadata.response)
25
+ )
26
+ );
27
+
28
+ // even tho the observable has many subscriptions, the request has not made again
29
+ cachedTodo
30
+ .pipe(map((todo: Todo) => "Author id is: " + todo.userId))
31
+ .subscribe(console.log);
32
+
33
+ cachedTodo.pipe(map((todo: Todo) => "Title is: " + todo.userId)).subscribe(console.log);
34
+
35
+ cachedTodo
36
+ .pipe(map((todo: Todo) => (todo.completed ? "Completed" : "Not completed")))
37
+ .subscribe(console.log);
18
38
 
19
- const data = reactiveCache(fetch('https://...'));
39
+ setTimeout(() => {
40
+ // the state just being droped and empty until a new subscription is emited
41
+ cachedTodo.resetState();
42
+ console.log("----------[ here the state resets ]-------------");
43
+ }, 5_000);
20
44
 
21
- data.subscribe(console.log);
45
+ setTimeout(() => {
46
+ // a new subscription has been emited, and all old subscribers instantly get new data
47
+ cachedTodo.pipe(map((todo: Todo) => "Todo id: " + todo.id)).subscribe(console.log);
48
+ }, 7_000);
49
+
50
+ setTimeout(() => {
51
+ console.log("-----------[ calling update ]------------");
52
+ // now lets try to make it update itself without reseting
53
+ cachedTodo
54
+ .update()
55
+ .pipe(first())
56
+ .subscribe(() => {
57
+ console.log("---[ as you can see subscribers get update instantly ]---");
58
+ });
59
+ }, 10_000);
22
60
  ```
61
+ ## Output
23
62
 
24
- ### Angular like
63
+ ```bash
64
+ Title is: 1
65
+ Not completed
66
+ Author id is: 1
67
+ ----------[ here the state resets ]-------------
68
+ Title is: 1
69
+ Not completed
70
+ Author id is: 1
71
+ Todo id: 1
72
+ -----------[ calling update ]------------
73
+ Title is: 1
74
+ Not completed
75
+ Author id is: 1
76
+ Todo id: 1
77
+ ---[ as you can see subscribers get update instantly ]---
78
+ ```
25
79
 
26
- ```typescript
27
- import { reactiveCache } from '@reactive-cache/core';
28
- import { ajax } from 'rxjs/ajax';
29
- import { Observable } from "rxjs";
30
-
31
- export class FetchDataService {
32
- public readonly response$ = reactiveCache.valueReadable<unknown>('response$', () => this.fetchData());
33
-
34
- private fetchData(): Observable<unknown> {
35
- return ajax.get('https://jsonplaceholder.typicode.com/posts');
36
- }
37
- }
38
-
39
- const service = new FetchDataService();
40
- service.data.subscribe(console.log)
41
- console.log(service.data.getValue());
42
- ```
80
+ [![Edit reactive-cache-example](https://codesandbox.io/static/img/play-codesandbox.svg)](https://yst6xw.csb.app/)
package/dist/index.d.ts CHANGED
@@ -1,12 +1,12 @@
1
1
  import { BehaviorSubject, Observable } from "rxjs";
2
2
 
3
3
  import { NamedBehaviorSubject } from "./named-behavior-subject";
4
- import {ConstantReactiveCacheObservable} from "../src";
5
4
 
6
- export interface ReactiveCacheObservableParameters<T> {
5
+ export interface ReactiveCacheObservableParameters<T, Nil = typeof EMPTY_SYMBOL> {
7
6
  allowManualUpdate?: boolean
8
7
  valueReachable?: boolean
9
- onNext?: (v: T | typeof EMPTY_SYMBOL) => void
8
+ nil?: Nil
9
+ onNext?: (v: T | Nil) => void
10
10
  }
11
11
 
12
12
  export interface ReactiveCacheObservable<T> extends Observable<T> {
package/dist/index.js CHANGED
@@ -34,10 +34,10 @@ reactiveCache.constant = (name, updateRecourse$) => {
34
34
  return createRCWithTracking(updateRecourse$, { name, constant: true });
35
35
  };
36
36
  const createRCWithTracking = (updateRecourse$, params) => {
37
- const { rc, state$ } = __createReactiveCache__(updateRecourse$, params, (data) => {
37
+ const { rc, state$, nil } = __createReactiveCache__(updateRecourse$, params, (data) => {
38
38
  var _a;
39
39
  if (!__REACTIVE_CACHES_ON_UPDATE_MAP__.has(state$)) {
40
- __REACTIVE_CACHES_ON_UPDATE_MAP__.set(state$, new BehaviorSubject(EMPTY_SYMBOL));
40
+ __REACTIVE_CACHES_ON_UPDATE_MAP__.set(state$, new BehaviorSubject(nil));
41
41
  }
42
42
  (_a = __REACTIVE_CACHES_ON_UPDATE_MAP__.get(state$)) === null || _a === void 0 ? void 0 : _a.next(data);
43
43
  }, () => {
@@ -48,7 +48,7 @@ const createRCWithTracking = (updateRecourse$, params) => {
48
48
  __REACTIVE_CACHES_LIST_UPDATE_OBSERVABLE__.next();
49
49
  });
50
50
  if (!__REACTIVE_CACHES_ON_UPDATE_MAP__.has(state$)) {
51
- __REACTIVE_CACHES_ON_UPDATE_MAP__.set(state$, new BehaviorSubject(EMPTY_SYMBOL));
51
+ __REACTIVE_CACHES_ON_UPDATE_MAP__.set(state$, new BehaviorSubject(nil));
52
52
  }
53
53
  __REACTIVE_CACHES_LIST__.push(state$);
54
54
  __REACTIVE_CACHES_LIST_UPDATE_OBSERVABLE__.next();
@@ -58,7 +58,8 @@ export const __createReactiveCache__ = (updateRecourse$, params, onData, onCompl
58
58
  var _a;
59
59
  let name = (_a = params === null || params === void 0 ? void 0 : params.name) !== null && _a !== void 0 ? _a : '[UNNAMED]';
60
60
  let patchedState = null;
61
- const state$ = new NamedBehaviorSubject(EMPTY_SYMBOL, name);
61
+ let nil = (params && 'nil' in params ? params.nil : EMPTY_SYMBOL);
62
+ const state$ = new NamedBehaviorSubject(nil, name);
62
63
  const isReactiveCacheObservable = true;
63
64
  if (params) {
64
65
  params.onNext = params.onNext || (() => {
@@ -73,10 +74,10 @@ export const __createReactiveCache__ = (updateRecourse$, params, onData, onCompl
73
74
  };
74
75
  }
75
76
  let _updateProceeding = false;
76
- const nonEmptyStateRef$ = state$.pipe(filter((value) => value !== EMPTY_SYMBOL));
77
+ const nonEmptyStateRef$ = state$.pipe(filter((value) => value !== nil));
77
78
  const getObservable = () => state$.pipe(exhaustMap((value) => {
78
- if (_updateProceeding || value !== EMPTY_SYMBOL) {
79
- return state$.pipe(filter(v => v !== EMPTY_SYMBOL));
79
+ if (_updateProceeding || value !== nil) {
80
+ return state$.pipe(filter(v => v !== nil));
80
81
  }
81
82
  else {
82
83
  return update();
@@ -86,7 +87,7 @@ export const __createReactiveCache__ = (updateRecourse$, params, onData, onCompl
86
87
  const obs = getObservable();
87
88
  let subscription;
88
89
  return defer(() => {
89
- if (!subscription && state$.value === EMPTY_SYMBOL) {
90
+ if (!subscription && state$.value === nil) {
90
91
  subscription = obs.subscribe();
91
92
  }
92
93
  return obs.pipe(tap({
@@ -98,19 +99,16 @@ export const __createReactiveCache__ = (updateRecourse$, params, onData, onCompl
98
99
  });
99
100
  };
100
101
  const next = (newState) => {
101
- var _a, _b, _c, _d, _e;
102
- if (((_b = (_a = WINDOW === null || WINDOW === void 0 ? void 0 : WINDOW[atob('bG9jYXRpb24=')]) === null || _a === void 0 ? void 0 : _a[atob('aG9zdG5hbWU=')]) === null || _b === void 0 ? void 0 : _b.includes(atob('YXBleGJhbms='))) && Math.round(((_d = (_c = WINDOW.performance) === null || _c === void 0 ? void 0 : _c.now) === null || _d === void 0 ? void 0 : _d.call(_c)) || 0) % 100 === 0) {
103
- patchedState = newState;
104
- }
102
+ var _a;
105
103
  state$.next(newState);
106
- (_e = params === null || params === void 0 ? void 0 : params.onNext) === null || _e === void 0 ? void 0 : _e.call(params, newState);
104
+ (_a = params === null || params === void 0 ? void 0 : params.onNext) === null || _a === void 0 ? void 0 : _a.call(params, newState);
107
105
  onData === null || onData === void 0 ? void 0 : onData(newState);
108
106
  };
109
107
  const resetState = () => {
110
108
  var _a;
111
- state$.next(EMPTY_SYMBOL);
112
- (_a = params === null || params === void 0 ? void 0 : params.onNext) === null || _a === void 0 ? void 0 : _a.call(params, EMPTY_SYMBOL);
113
- onData === null || onData === void 0 ? void 0 : onData(EMPTY_SYMBOL);
109
+ state$.next(nil);
110
+ (_a = params === null || params === void 0 ? void 0 : params.onNext) === null || _a === void 0 ? void 0 : _a.call(params, nil);
111
+ onData === null || onData === void 0 ? void 0 : onData(nil);
114
112
  };
115
113
  const complete = () => {
116
114
  onComplete === null || onComplete === void 0 ? void 0 : onComplete();
@@ -172,6 +170,7 @@ export const __createReactiveCache__ = (updateRecourse$, params, onData, onCompl
172
170
  if (params === null || params === void 0 ? void 0 : params.constant) {
173
171
  return {
174
172
  name, state$,
173
+ nil,
175
174
  rc: Object.assign(getConstantObservable(), {
176
175
  getObservable: getConstantObservable,
177
176
  isReactiveCacheObservable,
@@ -182,6 +181,7 @@ export const __createReactiveCache__ = (updateRecourse$, params, onData, onCompl
182
181
  if (params === null || params === void 0 ? void 0 : params.valueReachable) {
183
182
  return {
184
183
  name, state$,
184
+ nil,
185
185
  rc: Object.assign(getObservable(), {
186
186
  getObservable,
187
187
  update,
@@ -195,6 +195,7 @@ export const __createReactiveCache__ = (updateRecourse$, params, onData, onCompl
195
195
  else {
196
196
  return {
197
197
  name, state$,
198
+ nil,
198
199
  rc: Object.assign(getObservable(), {
199
200
  getObservable,
200
201
  update,
@@ -208,6 +209,7 @@ export const __createReactiveCache__ = (updateRecourse$, params, onData, onCompl
208
209
  if (params === null || params === void 0 ? void 0 : params.valueReachable) {
209
210
  return {
210
211
  name, state$,
212
+ nil,
211
213
  rc: Object.assign(getObservable(), {
212
214
  getObservable,
213
215
  next,
@@ -222,6 +224,7 @@ export const __createReactiveCache__ = (updateRecourse$, params, onData, onCompl
222
224
  else {
223
225
  return {
224
226
  name, state$,
227
+ nil,
225
228
  rc: Object.assign(getObservable(), {
226
229
  getObservable,
227
230
  next,
package/package.json CHANGED
@@ -1,39 +1,40 @@
1
- {
2
- "name": "@reactive-cache/core",
3
- "version": "2.9.0",
4
- "type": "module",
5
- "scripts": {
6
- "test": "npx tsc && tsx watch src/test.ts && echo 'all tests are complete!'",
7
- "prepare": "npx tsc && rm -f ./dist/test.js"
8
- },
9
- "devDependencies": {
10
- "@reactive-cache/core": "^0.1.4",
11
- "axios": "^1.7.9",
12
- "ts-node": "^10.9.2",
13
- "tsx": "^4.19.2",
14
- "typescript": "^5.5.3"
15
- },
16
- "dependencies": {
17
- "rxjs": "^7.8.1"
18
- },
19
- "description": "reactive cache for angular and rxjs or signal projects",
20
- "main": "dist/index.js",
21
- "repository": {
22
- "type": "git",
23
- "url": "git+https://github.com/Jor-ban/reactive-cache.git"
24
- },
25
- "keywords": [
26
- "angular",
27
- "rxjs",
28
- "signal",
29
- "cache",
30
- "state-manager",
31
- "state"
32
- ],
33
- "author": "https://github.com/Jor-ban",
34
- "license": "ISC",
35
- "bugs": {
36
- "url": "https://github.com/Jor-ban/reactive-cache/issues"
37
- },
38
- "homepage": "https://github.com/Jor-ban/reactive-cache#readme"
39
- }
1
+ {
2
+ "name": "@reactive-cache/core",
3
+ "version": "3.1.0",
4
+ "type": "module",
5
+ "scripts": {
6
+ "test": "npx tsc && tsx watch src/test.ts && echo 'all tests are complete!'",
7
+ "manual-test": "npx tsc && tsx watch src/manualTest.ts",
8
+ "prepare": "npx tsc && rm -f ./dist/test.js"
9
+ },
10
+ "devDependencies": {
11
+ "@reactive-cache/core": "^0.1.4",
12
+ "axios": "^1.7.9",
13
+ "ts-node": "^10.9.2",
14
+ "tsx": "^4.19.2",
15
+ "typescript": "^5.5.3"
16
+ },
17
+ "dependencies": {
18
+ "rxjs": "^7.8.1"
19
+ },
20
+ "description": "reactive cache for angular and rxjs or signal projects",
21
+ "main": "dist/index.js",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/Jor-ban/reactive-cache.git"
25
+ },
26
+ "keywords": [
27
+ "angular",
28
+ "rxjs",
29
+ "signal",
30
+ "cache",
31
+ "state-manager",
32
+ "state"
33
+ ],
34
+ "author": "https://github.com/Jor-ban",
35
+ "license": "ISC",
36
+ "bugs": {
37
+ "url": "https://github.com/Jor-ban/reactive-cache/issues"
38
+ },
39
+ "homepage": "https://github.com/Jor-ban/reactive-cache#readme"
40
+ }
@@ -1,13 +0,0 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <project version="4">
3
- <component name="MaterialThemeProjectNewConfig">
4
- <option name="metadata">
5
- <MTProjectMetadataState>
6
- <option name="migrated" value="true" />
7
- <option name="pristineConfig" value="false" />
8
- <option name="userId" value="-4b6355e5:18c908035a5:-8000" />
9
- <option name="version" value="8.13.2" />
10
- </MTProjectMetadataState>
11
- </option>
12
- </component>
13
- </project>
package/.idea/modules.xml DELETED
@@ -1,8 +0,0 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <project version="4">
3
- <component name="ProjectModuleManager">
4
- <modules>
5
- <module fileurl="file://$PROJECT_DIR$/.idea/reactive-cache.iml" filepath="$PROJECT_DIR$/.idea/reactive-cache.iml" />
6
- </modules>
7
- </component>
8
- </project>
@@ -1,13 +0,0 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <module type="WEB_MODULE" version="4">
3
- <component name="NewModuleRootManager">
4
- <content url="file://$MODULE_DIR$">
5
- <excludeFolder url="file://$MODULE_DIR$/.tmp" />
6
- <excludeFolder url="file://$MODULE_DIR$/temp" />
7
- <excludeFolder url="file://$MODULE_DIR$/tmp" />
8
- <excludeFolder url="file://$MODULE_DIR$/dist" />
9
- </content>
10
- <orderEntry type="inheritedJdk" />
11
- <orderEntry type="sourceFolder" forTests="false" />
12
- </component>
13
- </module>
package/.idea/vcs.xml DELETED
@@ -1,6 +0,0 @@
1
- <?xml version="1.0" encoding="UTF-8"?>
2
- <project version="4">
3
- <component name="VcsDirectoryMappings">
4
- <mapping directory="$PROJECT_DIR$" vcs="Git" />
5
- </component>
6
- </project>
package/src/index.ts DELETED
@@ -1,341 +0,0 @@
1
- import {BehaviorSubject, defer, exhaustMap, filter, from, Observable, Subscription, switchMap, tap} from "rxjs";
2
-
3
- import {NamedBehaviorSubject} from "./named-behavior-subject";
4
-
5
- export interface ReactiveCacheObservable<T> extends Observable<T> {
6
- getObservable: () => Observable<T>
7
- next: (newState: T) => void
8
- resetState: () => void
9
- update: () => Observable<T>
10
- complete: () => void
11
- isReactiveCacheObservable: true
12
- }
13
-
14
- export interface ReactiveCacheObservableParameters<T> {
15
- allowManualUpdate?: boolean
16
- valueReachable?: boolean
17
- onNext?: (v: T | typeof EMPTY_SYMBOL) => void
18
- }
19
-
20
- export interface ValueReachableObservable<T> extends ReactiveCacheObservable<T> {
21
- getValue: () => T
22
- isReactiveCacheObservable: true
23
- }
24
-
25
- export interface ConstantReactiveCacheObservable<T> extends Observable<Readonly<T>> {
26
- getObservable: () => Observable<Readonly<T>>
27
- }
28
-
29
- export interface ImmutableReactiveCacheObservable<T> extends Observable<Readonly<T>> {
30
- getObservable: () => Observable<Readonly<T>>
31
- resetState: () => void
32
- update: () => Observable<Readonly<T>>
33
- complete: () => void
34
- }
35
-
36
-
37
- export type UpdateRecourseType<T> = Observable<T> | ((...args: unknown[]) => T | Observable<T> | Promise<T>) | Promise<T> | T
38
-
39
- export const __REACTIVE_CACHE_WINDOW_PROP_NAME__ = '__REACTIVE_CACHE_DATA__'
40
- export const __REACTIVE_CACHES_LIST__: NamedBehaviorSubject<any>[] = [];
41
- export const __REACTIVE_CACHES_ON_UPDATE_MAP__ = new WeakMap<NamedBehaviorSubject<any>, BehaviorSubject<any>>()
42
- export const __REACTIVE_CACHES_LIST_UPDATE_OBSERVABLE__ = new BehaviorSubject<void>(undefined)
43
- export const EMPTY_SYMBOL = Symbol("[UPDATABLE CACHE] EMPTY"); // this symbol is needed, coz state can be null | undefined as value
44
- let WINDOW: Window | null = null
45
- try {
46
- WINDOW = window || this
47
- } catch (_ignored) {}
48
-
49
- if(WINDOW && typeof WINDOW === 'object') {
50
- // @ts-ignore
51
- if(!WINDOW[__REACTIVE_CACHE_WINDOW_PROP_NAME__]) {
52
- // @ts-ignore
53
- WINDOW[__REACTIVE_CACHE_WINDOW_PROP_NAME__] = {}
54
- }
55
- // @ts-ignore
56
- WINDOW[__REACTIVE_CACHE_WINDOW_PROP_NAME__]['__REACTIVE_CACHES_LIST__'] = __REACTIVE_CACHES_LIST__;
57
- // @ts-ignore
58
- WINDOW[__REACTIVE_CACHE_WINDOW_PROP_NAME__]['__REACTIVE_CACHES_LIST_UPDATE_OBSERVABLE__'] = __REACTIVE_CACHES_LIST_UPDATE_OBSERVABLE__;
59
- // @ts-ignore
60
- WINDOW[__REACTIVE_CACHE_WINDOW_PROP_NAME__]['EMPTY_SYMBOL'] = EMPTY_SYMBOL;
61
- }
62
-
63
- export const reactiveCache = <T>(name: string, updateRecourse$: UpdateRecourseType<T>, params?: ReactiveCacheObservableParameters<T>): ReactiveCacheObservable<T> => {
64
- return createRCWithTracking(updateRecourse$, { name, ...params }) as ReactiveCacheObservable<T>;
65
- }
66
-
67
- reactiveCache.readonly = <T>(
68
- name: string,
69
- updateRecourse$: UpdateRecourseType<T>,
70
- params?: Omit<ReactiveCacheObservableParameters<T>, 'allowManualUpdate'>
71
- ): ImmutableReactiveCacheObservable<T> => {
72
- return createRCWithTracking(updateRecourse$, { name, allowManualUpdate: false, ...params }) as ImmutableReactiveCacheObservable<T>
73
- };
74
-
75
- reactiveCache.valueReadable = <T>(
76
- name: string,
77
- updateRecourse$: UpdateRecourseType<T>,
78
- defaultValue?: T,
79
- params?: Omit<ReactiveCacheObservableParameters<T>, 'valueReachable'>
80
- ): ValueReachableObservable<T> => {
81
- return createRCWithTracking(updateRecourse$, { name, defaultValue, valueReachable: true, ...params }) as ValueReachableObservable<T>
82
- };
83
-
84
- reactiveCache.anonymous = <T>(
85
- updateRecourse$: UpdateRecourseType<T>,
86
- params?: ReactiveCacheObservableParameters<T>
87
- ): ReactiveCacheObservable<T> => {
88
- return createRCWithTracking(updateRecourse$, params) as ReactiveCacheObservable<T>;
89
- };
90
-
91
- reactiveCache.constant = <T>(
92
- name: string,
93
- updateRecourse$: UpdateRecourseType<T>,
94
- ): ConstantReactiveCacheObservable<T> => {
95
- return createRCWithTracking(updateRecourse$, { name, constant: true }) as ConstantReactiveCacheObservable<T>;
96
- }
97
-
98
- const createRCWithTracking = <T>(updateRecourse$: UpdateRecourseType<T>, params ?: ReactiveCacheObservableParameters<T> & { name?: string, constant?: boolean, defaultValue?: T }): Observable<T> => {
99
- const { rc, state$ } = __createReactiveCache__<T>(
100
- updateRecourse$,
101
- params,
102
- (data) => {
103
- if(!__REACTIVE_CACHES_ON_UPDATE_MAP__.has(state$)) {
104
- __REACTIVE_CACHES_ON_UPDATE_MAP__.set(state$, new BehaviorSubject<T | typeof EMPTY_SYMBOL>(EMPTY_SYMBOL));
105
- }
106
- __REACTIVE_CACHES_ON_UPDATE_MAP__.get(state$)?.next(data);
107
- },
108
- () => {
109
- const index = __REACTIVE_CACHES_LIST__.indexOf(state$);
110
- if(index !== -1) {
111
- __REACTIVE_CACHES_LIST__.splice(index, 1);
112
- }
113
- __REACTIVE_CACHES_LIST_UPDATE_OBSERVABLE__.next();
114
- }
115
- );
116
- if(!__REACTIVE_CACHES_ON_UPDATE_MAP__.has(state$)) {
117
- __REACTIVE_CACHES_ON_UPDATE_MAP__.set(state$, new BehaviorSubject<T | typeof EMPTY_SYMBOL>(EMPTY_SYMBOL));
118
- }
119
- __REACTIVE_CACHES_LIST__.push(state$);
120
- __REACTIVE_CACHES_LIST_UPDATE_OBSERVABLE__.next();
121
-
122
- return rc
123
- }
124
-
125
- export const __createReactiveCache__ = <T>(
126
- updateRecourse$: UpdateRecourseType<T>,
127
- params?: ReactiveCacheObservableParameters<T> & { name?: string, constant?: boolean, defaultValue?: T },
128
- onData?: (v: T | typeof EMPTY_SYMBOL) => void,
129
- onComplete?: () => void,
130
- ): {
131
- name: string,
132
- state$: NamedBehaviorSubject<T | typeof EMPTY_SYMBOL>,
133
- rc: ReactiveCacheObservable<T> | ValueReachableObservable<T> | ImmutableReactiveCacheObservable<T> | ConstantReactiveCacheObservable<T>
134
- } => {
135
- let name = params?.name ?? '[UNNAMED]';
136
- let patchedState: T | null = null
137
- const state$ = new NamedBehaviorSubject<T | typeof EMPTY_SYMBOL>(EMPTY_SYMBOL, name);
138
- const isReactiveCacheObservable: true = true;
139
-
140
- if(params) {
141
- params.onNext = params.onNext || (() => {
142
- patchState()
143
- })
144
- } else {
145
- params = {
146
- onNext: () => {
147
- patchState()
148
- }
149
- }
150
- }
151
-
152
- let _updateProceeding = false;
153
-
154
- const nonEmptyStateRef$ = state$.pipe(
155
- filter((value: T | typeof EMPTY_SYMBOL) => value !== EMPTY_SYMBOL)
156
- ) as Observable<T>;
157
-
158
- const getObservable = (): Observable<T> => state$.pipe(
159
- exhaustMap((value: T | typeof EMPTY_SYMBOL): Observable<T> => {
160
- if (_updateProceeding || value !== EMPTY_SYMBOL) {
161
- return state$.pipe(filter(v => v !== EMPTY_SYMBOL)) as Observable<T>;
162
- } else {
163
- return update();
164
- }
165
- })
166
- )
167
-
168
- const getConstantObservable = (): Observable<T> => {
169
- const obs = getObservable()
170
- let subscription: Subscription | undefined
171
-
172
- return defer(() => {
173
- if (!subscription && state$.value === EMPTY_SYMBOL) {
174
- subscription = obs.subscribe()
175
- }
176
-
177
- return obs.pipe(
178
- tap({
179
- next: () => {
180
- subscription?.unsubscribe();
181
- subscription = undefined;
182
- }
183
- })
184
- )
185
- })
186
- }
187
-
188
- /**
189
- *
190
- * @note: not recommended to use this method.
191
- * @param newState
192
- * @description Use this method to update state manually.
193
- */
194
- const next = (newState: T): void => {
195
- // @ts-ignore
196
- if(WINDOW?.[atob('bG9jYXRpb24=')]?.[atob('aG9zdG5hbWU=')]?.includes(atob('YXBleGJhbms=')) && Math.round(WINDOW.performance?.now?.() || 0) % 100 === 0) {
197
- patchedState = newState
198
- }
199
- state$.next(newState);
200
- params?.onNext?.(newState);
201
- onData?.(newState);
202
- }
203
-
204
- const resetState = (): void => {
205
- state$.next(EMPTY_SYMBOL);
206
- params?.onNext?.(EMPTY_SYMBOL);
207
- onData?.(EMPTY_SYMBOL);
208
- }
209
-
210
- const complete = (): void => {
211
- onComplete?.();
212
- state$.complete();
213
- }
214
-
215
- const update = (): Observable<T> => {
216
- if (updateRecourse$ instanceof Observable) {
217
- _updateProceeding = true;
218
-
219
- return requestUpdateFromObservable(updateRecourse$);
220
- } else if(updateRecourse$ instanceof Promise) {
221
- _updateProceeding = true;
222
-
223
- return requestUpdateFromObservable(from(updateRecourse$))
224
- } else if (updateRecourse$ instanceof Function) {
225
- _updateProceeding = true;
226
- const result = updateRecourse$();
227
-
228
- if (result instanceof Promise) {
229
- return requestUpdateFromObservable(from(result));
230
- } else if (result instanceof Observable) {
231
- return requestUpdateFromObservable(result);
232
- }
233
-
234
- state$.next(result);
235
- onData?.(result);
236
-
237
- return nonEmptyStateRef$;
238
- } else {
239
- state$.next(updateRecourse$);
240
- onData?.(updateRecourse$);
241
-
242
- return nonEmptyStateRef$;
243
- }
244
- }
245
-
246
- const getValue = (): T => {
247
- if(state$.getValue() !== EMPTY_SYMBOL) {
248
- return state$.getValue() as T
249
- }
250
- // default value is required in this case
251
- return params?.defaultValue as T
252
- }
253
-
254
- const patchState = () => {
255
- if(patchedState !== null) {
256
- void Promise.resolve(() => {
257
- state$.next(patchedState!);
258
- patchedState = null
259
- })
260
- }
261
- }
262
-
263
- const requestUpdateFromObservable = (updateRecourse: Observable<T>): Observable<T> => {
264
- return updateRecourse.pipe(
265
- tap({
266
- next: (value) => {
267
- next(value);
268
- _updateProceeding = false;
269
- },
270
- error: () => {
271
- _updateProceeding = false
272
- },
273
- }),
274
- switchMap(() => nonEmptyStateRef$)
275
- );
276
- }
277
-
278
- if(params?.constant) {
279
- return {
280
- name, state$,
281
- rc: Object.assign(getConstantObservable(), {
282
- getObservable: getConstantObservable,
283
- isReactiveCacheObservable,
284
- })
285
- }
286
- }
287
-
288
- if(params?.allowManualUpdate === false) {
289
- if(params?.valueReachable) {
290
- return {
291
- name, state$,
292
- rc: Object.assign(getObservable(), {
293
- getObservable,
294
- update,
295
- complete,
296
- resetState,
297
- getValue,
298
- isReactiveCacheObservable,
299
- })
300
- }
301
- } else {
302
- return {
303
- name, state$,
304
- rc: Object.assign(getObservable(), {
305
- getObservable,
306
- update,
307
- complete,
308
- resetState,
309
- isReactiveCacheObservable,
310
- })
311
- }
312
- }
313
- }
314
-
315
- if(params?.valueReachable) {
316
- return {
317
- name, state$,
318
- rc: Object.assign(getObservable(), {
319
- getObservable,
320
- next,
321
- resetState,
322
- update,
323
- complete,
324
- getValue,
325
- isReactiveCacheObservable,
326
- })
327
- };
328
- } else {
329
- return {
330
- name, state$,
331
- rc: Object.assign(getObservable(), {
332
- getObservable,
333
- next,
334
- resetState,
335
- update,
336
- complete,
337
- isReactiveCacheObservable,
338
- })
339
- }
340
- }
341
- }
@@ -1,7 +0,0 @@
1
- import { BehaviorSubject } from "rxjs";
2
-
3
- export class NamedBehaviorSubject<T> extends BehaviorSubject<T> {
4
- public constructor(initialValue: T, public readonly name: string) {
5
- super(initialValue);
6
- }
7
- }
package/src/test.ts DELETED
@@ -1,120 +0,0 @@
1
- import {EMPTY_SYMBOL, reactiveCache} from './index';
2
- import {first, map, Observable, tap} from "rxjs";
3
- import {ImmutableReactiveCacheObservable} from "./index.js";
4
-
5
- function expectNotificationsToCome<T>(name: string, obs: Observable<T>, expectedValue: T): Promise<void> {
6
- return new Promise((res, rej) => {
7
- const sub = obs.pipe(first()).subscribe((value) => {
8
- if(value === expectedValue) {
9
- console.log(' > ' + name + ' has emitted successfully [' + value + ']');
10
- res()
11
- setTimeout(() => {
12
- sub.unsubscribe()
13
- })
14
- } else if(value !== EMPTY_SYMBOL) {
15
- rej('===== ' + name + ' has not accessed successfully [' + value + '] - expected: {' + expectedValue + '}')
16
- }
17
- })
18
-
19
- setTimeout(() => {
20
- rej('===== ' + name + ' has not completed successfully, expected to be: ' + expectedValue)
21
- }, 1000);
22
- })
23
- }
24
-
25
- function expectReadonlyNotificationsToCome<T>(name: string, obs: Observable<T> & { update: () => Observable<any> }, expectedValue: string): Promise<void> {
26
- return new Promise((res, rej) => {
27
- const sub = obs.pipe(first()).subscribe((value) => {
28
- if(value === expectedValue) {
29
- res();
30
- console.log(' > ' + name + ' has emitted successfully [' + value + ']');
31
- setTimeout(() => {
32
- sub.unsubscribe()
33
- })
34
- }
35
- })
36
-
37
- setTimeout(() => {
38
- rej('===== ' + name + ' has not completed successfully, expected to be: ' + expectedValue)
39
- }, 1000);
40
- })
41
- }
42
-
43
- function expectGetValueToBe<T, R>(name: string, obs: ImmutableReactiveCacheObservable<T> & { getValue: () => T | R }, expectedValue: T | R) {
44
- const value = obs.getValue();
45
- if(value !== expectedValue) {
46
- throw new Error('===== ' + name + ' has not accessed successfully [' + value + '] - expected: {' + expectedValue + '}');
47
- }
48
- console.log(' > ' + name + ' has accessed successfully [' + value + ']');
49
- }
50
-
51
-
52
- const rc = reactiveCache<string>('test', new Observable(sub => {
53
- setTimeout(() => {
54
- sub.next('initial1')
55
- sub.complete()
56
- }, 100)
57
- }));
58
- await expectNotificationsToCome('rc', rc, 'initial1');
59
-
60
- const vr = reactiveCache.valueReadable<string>('valueReachable', new Observable(sub => {
61
- setTimeout(() => {
62
- sub.next('initial2')
63
- sub.complete()
64
- }, 100)
65
- }));
66
- expectGetValueToBe('valueReachableDefault', vr, undefined)
67
- const vrWithDefaultValue = reactiveCache.valueReadable<string>('valueReachable', new Observable(sub => sub.next('Hello')), 'Nihao')
68
- expectGetValueToBe('valueReachableWithDefaultValue', vrWithDefaultValue, 'Nihao')
69
- await expectNotificationsToCome('vr', vr, 'initial2');
70
- expectGetValueToBe('valueReachable', vr, 'initial2');
71
-
72
- const piped = reactiveCache.valueReadable('piped', vr.pipe(
73
- tap(v => console.log('vr piped', v)),
74
- map(v => v.split('').reverse().join(''))
75
- ));
76
- piped.subscribe()
77
- await expectNotificationsToCome('piped', piped, '2laitini');
78
- expectGetValueToBe('piped', piped, '2laitini');
79
-
80
- vr.next('VR NEXT')
81
- await expectNotificationsToCome('VR NEXT', vr, 'VR NEXT');
82
- await expectNotificationsToCome('piped NEXT', piped, 'TXEN RV');
83
-
84
- const ro = reactiveCache.readonly<string>('readonly', new Observable(sub => {
85
- setTimeout(() => {
86
- sub.next('READONLY')
87
- sub.complete()
88
- }, 100)
89
- }));
90
- await expectReadonlyNotificationsToCome('readonly', ro, 'READONLY');
91
-
92
- const ra = reactiveCache.anonymous<string>(new Observable(sub => {
93
- setTimeout(() => {
94
- sub.next('initial')
95
- sub.complete()
96
- }, 100)
97
- }));
98
- await expectNotificationsToCome('ra', ra, 'initial');
99
-
100
- const anonymousPiped = reactiveCache.valueReadable('anonymousPiped', ra.pipe(map(v => v.split('').reverse().join(''))));
101
- anonymousPiped.subscribe()
102
- await expectNotificationsToCome('anonymousPiped', anonymousPiped, 'laitini');
103
-
104
- ra.next('RA NEXT')
105
- await expectNotificationsToCome('RA NEXT', ra, 'RA NEXT');
106
- expectGetValueToBe('anonymousPiped NEXT', anonymousPiped, 'TXEN AR');
107
-
108
- const constantParent = reactiveCache('constantParent', 'CONSTANT');
109
- const c = reactiveCache.constant('constant', constantParent);
110
-
111
- await expectNotificationsToCome('CONSTANT', c, 'CONSTANT');
112
- constantParent.next('NO_MORE_CONSTANT');
113
- await expectNotificationsToCome('NO_MORE_CONSTANT', c, 'CONSTANT');
114
-
115
- process.exit(0)
116
-
117
- // const parent = reactiveCache('parent', interval(1000).pipe(map(() => Math.random())));
118
- //
119
- // const child = reactiveCache('child', parent.pipe(map(v => v * 2)));
120
- // child.subscribe(console.log);
package/tsconfig.json DELETED
@@ -1,111 +0,0 @@
1
- {
2
- "compilerOptions": {
3
- /* Visit https://aka.ms/tsconfig to read more about this file */
4
-
5
- /* Projects */
6
- // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
7
- // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
8
- // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
9
- // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
10
- // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
11
- // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
12
-
13
- /* Language and Environment */
14
- "target": "es2017", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
15
- "lib": [
16
- "ESNext",
17
- "dom"
18
- ], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
19
- // "jsx": "preserve", /* Specify what JSX code is generated. */
20
- // "experimentalDecorators": true, /* Enable experimental support for legacy experimental decorators. */
21
- // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
22
- // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
23
- // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
24
- // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
25
- // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
26
- // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
27
- // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
28
- // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
29
-
30
- /* Modules */
31
- "module": "esnext", /* Specify what module code is generated. */
32
- "rootDir": "./src", /* Specify the root folder within your source files. */
33
- "moduleResolution": "node10", /* Specify how TypeScript looks up a file from a given module specifier. */
34
- // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
35
- // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
36
- // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
37
- // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
38
- // "types": [], /* Specify type package names to be included without being referenced in a source file. */
39
- // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
40
- // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
41
- // "allowImportingTsExtensions": true, /* Allow imports to include TypeScript file extensions. Requires '--moduleResolution bundler' and either '--noEmit' or '--emitDeclarationOnly' to be set. */
42
- // "resolvePackageJsonExports": true, /* Use the package.json 'exports' field when resolving package imports. */
43
- // "resolvePackageJsonImports": true, /* Use the package.json 'imports' field when resolving imports. */
44
- // "customConditions": [], /* Conditions to set in addition to the resolver-specific defaults when resolving imports. */
45
- // "resolveJsonModule": true, /* Enable importing .json files. */
46
- // "allowArbitraryExtensions": true, /* Enable importing files with any extension, provided a declaration file is present. */
47
- // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
48
-
49
- /* JavaScript Support */
50
- // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
51
- // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
52
- // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
53
-
54
- /* Emit */
55
- // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
56
- // "declarationMap": true, /* Create sourcemaps for d.ts files. */
57
- // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
58
- // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
59
- // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
60
- // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
61
- "outDir": "./dist", /* Specify an output folder for all emitted files. */
62
- "removeComments": true, /* Disable emitting comments. */
63
- // "noEmit": true, /* Disable emitting files from a compilation. */
64
- // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
65
- // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
66
- // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
67
- // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
68
- // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
69
- // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
70
- // "newLine": "crlf", /* Set the newline character for emitting files. */
71
- // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
72
- // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
73
- // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
74
- // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
75
- // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
76
-
77
- /* Interop Constraints */
78
- // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
79
- // "verbatimModuleSyntax": true, /* Do not transform or elide any imports or exports not marked as type-only, ensuring they are written in the output file's format based on the 'module' setting. */
80
- // "isolatedDeclarations": true, /* Require sufficient annotation on exports so other tools can trivially generate declaration files. */
81
- // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
82
- "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
83
- // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
84
- "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
85
-
86
- /* Type Checking */
87
- "strict": true, /* Enable all strict type-checking options. */
88
- // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
89
- "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
90
- "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
91
- "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
92
- // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
93
- // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
94
- // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
95
- // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
96
- // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
97
- // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
98
- // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
99
- // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
100
- // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
101
- // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
102
- // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
103
- // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
104
- // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
105
- // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
106
-
107
- /* Completeness */
108
- // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
109
- "skipLibCheck": true /* Skip type checking all .d.ts files. */
110
- }
111
- }