Skip to content

Commit

Permalink
fix deriving from RxJS observables (sveltejs#4300)
Browse files Browse the repository at this point in the history
  • Loading branch information
Conduitry authored and taylorzane committed Dec 17, 2020
1 parent d1849c6 commit a060fda
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 14 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## Unreleased

* Fix updating a `<slot>` inside an `{#if}` or other block ([#4292](https://github.com/sveltejs/svelte/issues/4292))
* Fix using RxJS observables in `derived` stores ([#4298](https://github.com/sveltejs/svelte/issues/4298))

## 3.17.2

Expand Down
4 changes: 2 additions & 2 deletions src/runtime/internal/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ export function validate_store(store, name) {
}
}

export function subscribe(store, callback) {
const unsub = store.subscribe(callback);
export function subscribe(store, ...callbacks) {
const unsub = store.subscribe(...callbacks);
return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}

Expand Down
5 changes: 3 additions & 2 deletions src/runtime/store/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { run_all, noop, safe_not_equal, is_function, get_store_value } from 'svelte/internal';
import { run_all, subscribe, noop, safe_not_equal, is_function, get_store_value } from 'svelte/internal';

/** Callback to inform of a value updates. */
type Subscriber<T> = (value: T) => void;
Expand Down Expand Up @@ -173,7 +173,8 @@ export function derived<T>(stores: Stores, fn: Function, initial_value?: T): Rea
}
};

const unsubscribers = stores_array.map((store, i) => store.subscribe(
const unsubscribers = stores_array.map((store, i) => subscribe(
store,
(value) => {
values[i] = value;
pending &= ~(1 << i);
Expand Down
25 changes: 15 additions & 10 deletions test/store/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,15 @@ describe('store', () => {
});
});

const fake_observable = {
subscribe(fn) {
fn(42);
return {
unsubscribe: () => {}
};
}
};

describe('derived', () => {
it('maps a single store', () => {
const a = writable(1);
Expand Down Expand Up @@ -346,6 +355,11 @@ describe('store', () => {
b.set(2);
assert.deepEqual(get(c), 'two 2');
});

it('works with RxJS-style observables', () => {
const d = derived(fake_observable, _ => _);
assert.equal(get(d), 42);
});
});

describe('get', () => {
Expand All @@ -355,16 +369,7 @@ describe('store', () => {
});

it('works with RxJS-style observables', () => {
const observable = {
subscribe(fn) {
fn(42);
return {
unsubscribe: () => {}
};
}
};

assert.equal(get(observable), 42);
assert.equal(get(fake_observable), 42);
});
});
});

0 comments on commit a060fda

Please sign in to comment.