@@ -44,6 +44,8 @@ export interface Writable<T> extends Readable<T> {
44
44
/** Pair of subscriber and invalidator. */
45
45
type SubscribeInvalidateTuple < T > = [ Subscriber < T > , Invalidator < T > ] ;
46
46
47
+ const subscriber_queue = [ ] ;
48
+
47
49
/**
48
50
* Creates a `Readable` store that allows reading by subscription.
49
51
* @param value initial value
@@ -67,11 +69,20 @@ export function writable<T>(value: T, start: StartStopNotifier<T> = noop): Writa
67
69
function set ( new_value : T ) : void {
68
70
if ( safe_not_equal ( value , new_value ) ) {
69
71
value = new_value ;
70
- if ( ! stop ) {
71
- return ; // not ready
72
+ if ( stop ) { // store is ready
73
+ const run_queue = ! subscriber_queue . length ;
74
+ for ( let i = 0 ; i < subscribers . length ; i += 1 ) {
75
+ const s = subscribers [ i ] ;
76
+ s [ 1 ] ( ) ;
77
+ subscriber_queue . push ( s , value ) ;
78
+ }
79
+ if ( run_queue ) {
80
+ for ( let i = 0 ; i < subscriber_queue . length ; i += 2 ) {
81
+ subscriber_queue [ i ] [ 0 ] ( subscriber_queue [ i + 1 ] ) ;
82
+ }
83
+ subscriber_queue . length = 0 ;
84
+ }
72
85
}
73
- subscribers . forEach ( ( s ) => s [ 1 ] ( ) ) ;
74
- subscribers . forEach ( ( s ) => s [ 0 ] ( value ) ) ;
75
86
}
76
87
}
77
88
@@ -129,9 +140,7 @@ export function derived<T, S extends Stores>(
129
140
130
141
const auto = fn . length < 2 ;
131
142
132
- const invalidators : Array < Invalidator < T > > = [ ] ;
133
-
134
- const store = readable ( initial_value , ( set ) => {
143
+ return readable ( initial_value , ( set ) => {
135
144
let inited = false ;
136
145
const values : StoresValues < S > = [ ] as StoresValues < S > ;
137
146
@@ -160,7 +169,6 @@ export function derived<T, S extends Stores>(
160
169
}
161
170
} ,
162
171
( ) => {
163
- run_all ( invalidators ) ;
164
172
pending |= ( 1 << i ) ;
165
173
} ) ,
166
174
) ;
@@ -173,20 +181,4 @@ export function derived<T, S extends Stores>(
173
181
cleanup ( ) ;
174
182
} ;
175
183
} ) ;
176
-
177
- return {
178
- subscribe ( run : Subscriber < T > , invalidate : Invalidator < T > = noop ) : Unsubscriber {
179
- invalidators . push ( invalidate ) ;
180
-
181
- const unsubscribe = store . subscribe ( run , invalidate ) ;
182
-
183
- return ( ) => {
184
- const index = invalidators . indexOf ( invalidate ) ;
185
- if ( index !== - 1 ) {
186
- invalidators . splice ( index , 1 ) ;
187
- }
188
- unsubscribe ( ) ;
189
- } ;
190
- }
191
- } ;
192
- }
184
+ }
0 commit comments