handle rxjs-style observables with get_store_value - fixes #3153

pull/3170/head
Rich Harris 5 years ago
parent 943c04834a
commit 2d5f11a308

@ -114,9 +114,15 @@ export function create_ssr_component(fn) {
}; };
} }
/**
* Get the current value from a store by subscribing and immediately unsubscribing.
* @param store readable
*/
export function get_store_value<T>(store: Readable<T>): T | undefined { export function get_store_value<T>(store: Readable<T>): T | undefined {
let value; let value;
store.subscribe(_ => value = _)(); const unsubscribe: any = store.subscribe(_ => value = _);
if (unsubscribe.unsubscribe) unsubscribe.unsubscribe();
else unsubscribe();
return value; return value;
} }

@ -1,4 +1,5 @@
import { run_all, noop, safe_not_equal, is_function } from 'svelte/internal'; import { run_all, noop, safe_not_equal, is_function } from 'svelte/internal';
export { get_store_value as get } from 'svelte/internal';
/** Callback to inform of a value updates. */ /** Callback to inform of a value updates. */
type Subscriber<T> = (value: T) => void; type Subscriber<T> = (value: T) => void;
@ -189,13 +190,3 @@ export function derived<T, S extends Stores>(
} }
}; };
} }
/**
* Get the current value from a store by subscribing and immediately unsubscribing.
* @param store readable
*/
export function get<T>(store: Readable<T>): T {
let value: T | undefined;
store.subscribe((_: T) => value = _)();
return value as T;
}

@ -329,5 +329,18 @@ describe('store', () => {
const store = readable(42, () => { }); const store = readable(42, () => { });
assert.equal(get(store), 42); assert.equal(get(store), 42);
}); });
it('works with RxJS-style observables', () => {
const observable = {
subscribe(fn) {
fn(42);
return {
unsubscribe: () => {}
}
}
};
assert.equal(get(observable), 42);
});
}); });
}); });

Loading…
Cancel
Save