|
1 | | -import { type FetchOpts, Resource } from '@tomic/lib'; |
| 1 | +import { type FetchOpts, Resource, Store } from '@tomic/lib'; |
2 | 2 |
|
3 | | -import { type Readable, get, readable } from 'svelte/store'; |
| 3 | +import { type Readable, get, readable, Subscriber } from 'svelte/store'; |
4 | 4 | import { store } from './store'; |
5 | 5 |
|
6 | | -export const getResource = ( |
| 6 | +const subscribeToADStore = ( |
| 7 | + adStore: Store, |
7 | 8 | subject: string, |
| 9 | + set: Subscriber<Resource>, |
| 10 | + opts?: FetchOpts, |
| 11 | +) => { |
| 12 | + set(adStore.getResourceLoading(subject, opts)); |
| 13 | + |
| 14 | + const subscriber = (changedResource: Resource) => { |
| 15 | + set(changedResource); |
| 16 | + }; |
| 17 | + |
| 18 | + adStore.subscribe(subject, subscriber); |
| 19 | + |
| 20 | + return () => { |
| 21 | + adStore.unsubscribe(subject, subscriber); |
| 22 | + }; |
| 23 | +}; |
| 24 | + |
| 25 | +export const getResource = ( |
| 26 | + subject: string | Readable<string>, |
8 | 27 | opts?: FetchOpts, |
9 | 28 | ): Readable<Resource> => { |
10 | 29 | const adStore = get(store); |
11 | 30 |
|
| 31 | + const subjectValue = typeof subject === 'string' ? subject : get(subject); |
| 32 | + |
12 | 33 | // eslint-disable-next-line prefer-const |
13 | 34 | let resource = readable<Resource>( |
14 | | - adStore.getResourceLoading(subject, opts), |
| 35 | + adStore.getResourceLoading(subjectValue, opts), |
15 | 36 | set => { |
16 | | - set(adStore.getResourceLoading(subject, opts)); |
| 37 | + if (typeof subject !== 'string') { |
| 38 | + let atomicUnsubscriber: () => void; |
17 | 39 |
|
18 | | - const subscriber = (changedResource: Resource) => { |
19 | | - set(changedResource); |
20 | | - }; |
| 40 | + const subjectUnsubscriber = subject.subscribe(value => { |
| 41 | + atomicUnsubscriber?.(); |
21 | 42 |
|
22 | | - adStore.subscribe(subject, subscriber); |
| 43 | + set(adStore.getResourceLoading(value, opts)); |
| 44 | + atomicUnsubscriber = subscribeToADStore(adStore, value, set, opts); |
| 45 | + }); |
23 | 46 |
|
24 | | - return () => adStore.unsubscribe(subject, subscriber); |
| 47 | + return () => { |
| 48 | + subjectUnsubscriber(); |
| 49 | + atomicUnsubscriber?.(); |
| 50 | + }; |
| 51 | + } else { |
| 52 | + return subscribeToADStore(adStore, subject, set, opts); |
| 53 | + } |
25 | 54 | }, |
26 | 55 | ); |
27 | 56 |
|
|
0 commit comments