Skip to content

Commit

Permalink
handle rxjs-style observables with get_store_value - fixes #3153
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich-Harris committed Jul 3, 2019
1 parent 943c048 commit 2d5f11a
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 12 deletions.
8 changes: 7 additions & 1 deletion src/runtime/internal/ssr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
let value;
store.subscribe(_ => value = _)();
const unsubscribe: any = store.subscribe(_ => value = _);
if (unsubscribe.unsubscribe) unsubscribe.unsubscribe();
else unsubscribe();
return value;
}

Expand Down
13 changes: 2 additions & 11 deletions src/runtime/store/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
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. */
type Subscriber<T> = (value: T) => void;
Expand Down Expand Up @@ -188,14 +189,4 @@ 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;
}
}
13 changes: 13 additions & 0 deletions test/store/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,5 +329,18 @@ describe('store', () => {
const store = readable(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);
});
});
});

0 comments on commit 2d5f11a

Please sign in to comment.