File tree Expand file tree Collapse file tree 2 files changed +25
-1
lines changed Expand file tree Collapse file tree 2 files changed +25
-1
lines changed Original file line number Diff line number Diff line change @@ -34,7 +34,8 @@ export function readable(start, value) {
34
34
} ;
35
35
}
36
36
37
- export function writable ( value ) {
37
+ export function writable ( value , start = noop ) {
38
+ let stop ;
38
39
const subscribers = [ ] ;
39
40
40
41
function set ( newValue ) {
@@ -51,11 +52,13 @@ export function writable(value) {
51
52
function subscribe ( run , invalidate = noop ) {
52
53
const subscriber = [ run , invalidate ] ;
53
54
subscribers . push ( subscriber ) ;
55
+ if ( subscribers . length === 1 ) stop = start ( ) || noop ;
54
56
run ( value ) ;
55
57
56
58
return ( ) => {
57
59
const index = subscribers . indexOf ( subscriber ) ;
58
60
if ( index !== - 1 ) subscribers . splice ( index , 1 ) ;
61
+ if ( subscribers . length === 0 ) stop ( ) ;
59
62
} ;
60
63
}
61
64
Original file line number Diff line number Diff line change @@ -21,6 +21,27 @@ describe('store', () => {
21
21
22
22
assert . deepEqual ( values , [ 0 , 1 , 2 ] ) ;
23
23
} ) ;
24
+
25
+ it ( 'calls provided subscribe handler' , ( ) => {
26
+ let called = 0 ;
27
+
28
+ const store = writable ( 0 , ( ) => {
29
+ called += 1 ;
30
+ return ( ) => called -= 1 ;
31
+ } ) ;
32
+
33
+ const unsubscribe1 = store . subscribe ( ( ) => { } ) ;
34
+ assert . equal ( called , 1 ) ;
35
+
36
+ const unsubscribe2 = store . subscribe ( ( ) => { } ) ;
37
+ assert . equal ( called , 1 ) ;
38
+
39
+ unsubscribe1 ( ) ;
40
+ assert . equal ( called , 1 ) ;
41
+
42
+ unsubscribe2 ( ) ;
43
+ assert . equal ( called , 0 ) ;
44
+ } ) ;
24
45
} ) ;
25
46
26
47
describe ( 'readable' , ( ) => {
You can’t perform that action at this time.
0 commit comments